需求 :
编写一个方法,接受第一个参数FIle fromFile,接受第二参数 File toFile;将 fromFIle 文件内容复制到 toFile中。
代码:
package work;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
File srcFile = new File("C:/eclipse.zip");
File destFile = new File("D:/eclipse.zip");
boolean copyFile = Main.copyFile(srcFile, destFile);
System.out.println(copyFile);
}
/**
* 文件的复制
*
* @param srcFile
* 拷贝的文件路径的描述
* @param destFile
* 粘贴的文件路径的描述
* @return 成功与否
*/
public static boolean copyFile(File srcFile, File destFile) {
if (srcFile == null || destFile == null) {
return false;
}
try (FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile)) {
byte[] b = new byte[1024];
int read = 0;
while ((read = fis.read(b)) != -1) {
fos.write(b, 0, read);
}
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}