import java.io.*;
public class CopyFile2 {
public static void main(String[] args) throws IOException {
copyFileName("E:\\图片", "E:\\");
}
// 将文件1复制到文件2的目录下
public static void copyFileName(String s1, String s2) throws IOException {
File file1 = new File(s1);
if (!file1.exists()) { // 文件1不存在,退出
return;
}
String name1 = file1.getName();
if (file1.getParent().equals(s2)) { // 第一次处理同名情况,加" - 副本"
if (file1.isFile()) {
String[] split = name1.split("."); // 处理特殊名文件夹,如"fd.fr.txt"
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length - 1; i++) {
sb.append(split[i]);
}
name1 = sb.toString() + " - 副本" + split[split.length - 1];
} else {
name1 += " - 副本";
}
}
File file2 = new File(s2 + name1);
copyFiles(file1, file2);
}
// 将文件1复制到文件2,file1与file2同级
public static void copyFiles(File file1, File file2) throws IOException {
if (file1.isFile()) { // 文件1是文件,复制
copyFile(file1, file2); // 复制文件
return;
}
// file1是文件夹,创建file2文件夹
file2.mkdir();
File[] files = file1.listFiles(); // 得到文件夹1的目录
if (files != null) {
for (File file1_1 : files) { // 遍历目录
copyFiles(file1_1, new File(file2, file1_1.getName())); // 递归复制
}
}
}
// 将文件1复制到文件2
public static void copyFile(File file1, File file2) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file1));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2));
byte[] bytes = new byte[1024];
int read = 0;
while ((read = bis.read(bytes)) != -1) {
bos.write(bytes, 0, read);
}
bis.close();
bos.close();
}
}
IO流 文件复制
最新推荐文章于 2024-01-08 22:26:03 发布