Here you can find the source of copyFile(File src, File dst)
Parameter | Description |
---|---|
src | Origin file |
dst | Destination FOLDER. |
Parameter | Description |
---|---|
FileNotFoundException | an exception |
public static void copyFile(File src, File dst) throws FileNotFoundException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; public class Main { /**//from ww w . jav a2 s .c o m * Copy a file to another folder * @param src Origin file * @param dst Destination FOLDER. * @throws FileNotFoundException */ public static void copyFile(File src, File dst) throws FileNotFoundException { if (src == null) { throw new IllegalArgumentException("File src can't be null!!"); } if (dst == null) { throw new IllegalArgumentException("File dst can't be null!!"); } if (!src.exists()) { throw new FileNotFoundException("File " + src.getName() + " can't be found!"); } if (!dst.exists()) { dst.mkdirs(); } dst = new File(dst.getPath() + "/" + src.getName()); if (!isFileInUse(src)) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(src).getChannel(); out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } } /** * Tests if the file specified is being used by another process * @param file File to be tested * @return true if the file is being used, false otherwise */ public static boolean isFileInUse(File file) { boolean result = false; FileChannel fc = null; try { fc = new RandomAccessFile(file, "rw").getChannel(); } catch (FileNotFoundException e) { if (!file.exists()) { System.err.println("The file " + file.getName() + " not exists!!"); } else { System.out.println("The file " + file.getName() + " is in use by another process!!"); result = true; } } finally { if (fc != null) { try { fc.close(); } catch (IOException e) { e.printStackTrace(); } } else { return result; } } return false; } }