Here you can find the source of copy(File file, File toDirectory)
Parameter | Description |
---|---|
file | the file to be copied. |
toDirectory | the directory to which the file should be copied. |
Parameter | Description |
---|---|
IOException | in case of errors |
public static File copy(File file, File toDirectory) throws IOException
//package com.java2s; //License from project: Apache 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 { /**/*from w w w. jav a2s . c o m*/ * Copies a file to the specified directory. * * @param file the file to be copied. * @param toDirectory the directory to which the file should be copied. * * @return file object to the copied file. * * @throws IOException in case of errors */ public static File copy(File file, File toDirectory) throws IOException { if (file == null || !file.exists() || !file.canRead()) { throw new IOException("Unable to find source file to be copied " + file); } String basename = file.getName(); File destFile = new File(toDirectory, basename.toString()); if (!toDirectory.exists()) toDirectory.createNewFile(); FileChannel fcSrc = null; FileChannel fcDst = null; try { fcSrc = new FileInputStream(file).getChannel(); fcDst = new FileOutputStream(destFile).getChannel(); fcDst.transferFrom(fcSrc, 0, fcSrc.size()); } finally { if (fcSrc != null) fcSrc.close(); if (fcDst != null) fcDst.close(); } return destFile; } }