Here you can find the source of overwriteFile(final String newFilePath, final String oldFilePath)
Parameter | Description |
---|---|
newFilePath | the source file to use |
oldFilePath | the destination file to overwrite with the contents of the source file |
Parameter | Description |
---|---|
IOException | if there is an error opening either of the files or copying the source file'scontents into the destination file |
public static void overwriteFile(final String newFilePath, final String oldFilePath) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class Main { /** Overwrite the destination file with the source file * @param newFilePath the source file to use * @param oldFilePath the destination file to overwrite with the contents of the source file * @throws IOException if there is an error opening either of the files or copying the source file's * contents into the destination file *//*from w w w. j av a 2 s .c o m*/ public static void overwriteFile(final String newFilePath, final String oldFilePath) throws IOException { FileChannel src = null; FileChannel dest = null; try { File oldFile = new File(oldFilePath).getCanonicalFile(); File newFile = new File(newFilePath).getCanonicalFile(); //System.out.println("Overwriting: " + oldFile.getAbsolutePath() + ", with: " + newFile.getAbsolutePath()); if (!oldFile.isFile()) { throw new IOException("old file path does not exist (" + oldFilePath + ")"); } if (!newFile.isFile()) { throw new IOException("new file path does not exist (" + newFilePath + ")"); } src = new FileInputStream(newFile).getChannel(); dest = new FileOutputStream(oldFile).getChannel(); long transferCount = 0; long size = src.size(); do { transferCount += dest.transferFrom(src, transferCount, size - transferCount); } while (transferCount < size); } catch (IOException e) { throw e; } finally { try { if (src != null) { src.close(); } if (dest != null) { dest.close(); } } catch (IOException e) { e.printStackTrace(); } } } }