Here you can find the source of renameFile(File srcFile, File dstFile)
Parameter | Description |
---|---|
srcFile | source file |
dstFile | destination file |
Parameter | Description |
---|---|
IOException | if any exception occurred |
public static void renameFile(File srcFile, File dstFile) throws IOException
//package com.java2s; /*// w ww.j a v a2 s .c om * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /** * Rename file. If file can't be renamed in standard way the coping * data will be used instead. * * @param srcFile * source file * @param dstFile * destination file * @throws IOException * if any exception occurred */ public static void renameFile(File srcFile, File dstFile) throws IOException { // Rename the srcFile file to the new one. Unfortunately, the renameTo() // method does not work reliably under some JVMs. Therefore, if the // rename fails, we manually rename by copying the srcFile file to the new one if (!srcFile.renameTo(dstFile)) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(dstFile); transfer(in, out); } catch (IOException ioe) { IOException newExc = new IOException("Cannot rename " + srcFile + " to " + dstFile); newExc.initCause(ioe); throw newExc; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } // delete the srcFile file. srcFile.delete(); } } /** * Transfer bytes from in to out */ public static void transfer(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[2048]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } }