Here you can find the source of copyFile(File srcFile, File destFile, boolean createCopy)
Parameter | Description |
---|---|
srcFile | a parameter |
destFile | a parameter |
createCopy | If this is true and the destination file exists, the file is copied such as "myfile(1).txt" |
Parameter | Description |
---|---|
IOException | an exception |
public static void copyFile(File srcFile, File destFile, boolean createCopy) throws IOException
//package com.java2s; import java.io.BufferedInputStream; 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. j a v a 2s . c om * Copy a File. The Source file must exist. * @param srcFile * @param destFile * @param createCopy If this is true and the destination file exists, the file is copied such as "myfile(1).txt" * @throws IOException */ public static void copyFile(File srcFile, File destFile, boolean createCopy) throws IOException { if (createCopy) { if (srcFile.equals(destFile) || destFile.exists()) { int i = 1; String name = getFileNameWithoutExtension(srcFile); String ext = getFileExtension(srcFile); do { destFile = new File(destFile.getParentFile(), name + "(" + i++ + ")" + ext); //$NON-NLS-1$ //$NON-NLS-2$ } while (destFile.exists()); } } else { if (srcFile.equals(destFile)) { throw new IOException("Source and Target Files cannot be the same"); //$NON-NLS-1$ } } int bufSize = 1024; byte[] buf = new byte[bufSize]; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile), bufSize); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile), bufSize); int size; while ((size = bis.read(buf)) != -1) { bos.write(buf, 0, size); } bos.flush(); bos.close(); bis.close(); } /** * Get the short name portion of a filename not including the extension. * @param file The File in question * @return The name part of a file name excluding the extension */ public static String getFileNameWithoutExtension(File file) { String fileName = file.getName(); int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) { return fileName.substring(0, i); } else { return fileName; } } /** * Get the extension portion of a filename. * @param file The File in question * @return The extension part of the filename including the "." or "" if no extension */ public static String getFileExtension(File file) { String fileName = file.getName(); int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) { return fileName.substring(i).toLowerCase(); } return ""; //$NON-NLS-1$ } }