方法一:简单粗暴,直接使用copy(),如果目标存在,先使用delete()删除,再复制;
方法二:使用输入输出流。(代码注释部分)
代码语言:javascript复制package eg2;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Scanner;
/******************
* 文件的复制
*******************/
public class Test2_3 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("请输入指定文件夹路径:");
String oldpath = sc.next();
System.out.println("请输入目标文件夹路径:");
String newpath = sc.next();
System.out.println("请输入要复制的文件名:");
String filename = sc.next();
copy(filename, oldpath, newpath);
System.out.println("复制完成!");
}
private static void copy(String filename, String oldpath, String newpath) throws IOException {
// TODO Auto-generated method stub
File oldpaths = new File(oldpath "/" filename);
File newpaths = new File(newpath "/" filename);
if (!newpaths.exists()) {
Files.copy(oldpaths.toPath(), newpaths.toPath());
} else {
newpaths.delete();
Files.copy(oldpaths.toPath(), newpaths.toPath());
}
// String newfile = "";
// newfile = newpaths;
// FileInputStream in = new FileInputStream(oldpaths);
// File file = new File(newfile);
// if (!file.exists()) {
// file.createNewFile();
// }
// FileOutputStream out = new FileOutputStream(newpaths);
// byte[] buffer = new byte[1024];
// int c;
// while ((c = in.read(buffer)) != -1) {
// for (int i = 0; i < c; i ) {
// out.write(buffer[i]);
// }
// }
// in.close();
// out.close();
}
}