62,615
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
import java.io.*;
public class Copy {
public void abcd () {
File fromFile = new File ("c:\\1.txt");
File toFile = new File ("c:\\2.txt");
copyFile(fromFile, toFile);
}
// 复制一个文件
public void copyFile(File fromFile, File toFile) {// 复制文件
createFile(toFile, true);// 创建文件
System.out.println("复制文件" + fromFile.getAbsolutePath() + "到" + toFile.getAbsolutePath());
try {
FileOutputStream fop = new FileOutputStream(toFile); // 创建FileOutputStream对象
FileInputStream in = new FileInputStream(fromFile);
int tempbyte;
byte[] buffer = new byte[1024];
int readNum; //这里添加一个变量用于记录已读的字符数
while ((readNum = in.read(buffer)) != -1) { // 循环读取文件
fop.write(buffer, 0, readNum); // 通过流写数据
}
fop.close(); // 关闭输出流
in.close(); // 关闭输入流
} catch (IOException e) {
e.printStackTrace();
}
}
public void createFile(File file, boolean isFile) {// 创建文件
if (!file.exists()) {// 如果文件不存在
if (!file.getParentFile().exists()) {// 如果文件父目录不存在
createFile(file.getParentFile(), false);
} else {// 存在文件父目录
if (isFile) {// 创建文件
try {
file.createNewFile();// 创建新文件
} catch (IOException e) {
e.printStackTrace();
}
} else {
file.mkdirs();// 创建目录
}
}
}
}
public static void main(String[] args) {
long sttime = System.nanoTime();
Copy sourceToDestiny = new Copy();
sourceToDestiny.abcd();
long endtime = System.nanoTime();
System.out.println("Totaol time is: "+(endtime-sttime)/1000000000+"秒");
}
}