Here you can find the source of rename(File from, File to)
Parameter | Description |
---|---|
from | a parameter |
to | a parameter |
Parameter | Description |
---|---|
IOException | an exception |
public static void rename(File from, File to) throws IOException
//package com.java2s; import java.io.*; public class Main { /**// w w w . java2s .c om * rename file * * @param from * @param to * @throws IOException */ public static void rename(File from, File to) throws IOException { if (to.exists() && !to.delete()) { throw new IOException("Failed to delete " + to + " while trying to rename " + from); } File parent = to.getParentFile(); if (parent != null && !parent.exists() && !parent.mkdirs()) { throw new IOException("Failed to create directory " + parent + " while trying to rename " + from); } if (!from.renameTo(to)) { copyFile(from, to); if (!from.delete()) { throw new IOException("Failed to delete " + from + " while trying to rename it."); } } } /** * file delete method * * @param file */ public static void delete(File file) { if (file != null) { if (file.exists()) { file.delete(); } } } public static void copyFile(File source, File target) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(source)); out = new BufferedOutputStream(new FileOutputStream(target)); int ch; while ((ch = in.read()) != -1) { out.write(ch); } out.flush(); // just in case } finally { if (out != null) try { out.close(); } catch (IOException ioe) { } if (in != null) try { in.close(); } catch (IOException ioe) { } } } }