Here you can find the source of copyFile(File sourceFile, File destDir)
Parameter | Description |
---|---|
sourceFile | The source file. |
destDir | The destination dir, not a file. |
public static final void copyFile(File sourceFile, File destDir) throws IOException
//package com.java2s; //License from project: Apache License import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Main { /**//from w w w . ja va 2 s . c o m * Copy source file to dest dir. * @param sourceFile The source file. * @param destDir The destination dir, not a file. */ public static final void copyFile(File sourceFile, File destDir) throws IOException { boolean copy = false; File destFile = new File(destDir, sourceFile.getName()); if (!destFile.exists()) { copy = true; } else if (sourceFile.lastModified() > destFile.lastModified()) { copy = true; } if (copy) { BufferedOutputStream bos = null; try { FileOutputStream fos = new FileOutputStream(destFile); bos = new BufferedOutputStream(fos); byte[] raw = readFileBytes(sourceFile.getAbsolutePath()); bos.write(raw); } finally { bos.close(); bos = null; } } } /** * Read the file raw content into byte array. * @param fileName * @return */ public static final byte[] readFileBytes(String fileName) throws IOException { File file = new File(fileName); return readFileBytes(file); } /** * Read the file raw content into byte array. * @param fileName * @return */ public static final byte[] readFileBytes(File file) throws IOException { if (file.exists() && file.isFile()) { FileInputStream fis = new FileInputStream(file); int fileLen = (int) file.length(); byte[] buf = new byte[fileLen]; int len = 0; while (len < fileLen) { int n = fis.read(buf, len, fileLen - len); if (n >= 0) { len += n; } else { break; } } return buf; } else { throw new IOException(file + " does not exist or is not file!"); } } }