/**
* 编写一个程序,我想把这个目录下的所有带.java文件拷贝到另一个目录下,拷贝成功以后把后缀名是.java改成.txt
*/
public static void main(String[] args) throws Exception {
File src = getfile();
File dest = getfile();
if (src.equals(dest)) {
System.out.println("目标文件是原文件夹的子文件夹");
} else {
copy(src, dest);
}
rename(dest);
}
private static void rename(File dest) {
File[] subfiles = dest.listFiles(); // 获取目标文件夹下的文件和文件夹
for (File subfile : subfiles) {
if (subfile.isFile()) {
if (subfile.getName().endsWith(".java")) {
System.out.println(subfile.getPath().replaceAll("\\.java", ".txt"));
File newName = new File(subfile.getPath().replaceAll("\\.java",".txt"));
subfile.renameTo(newName);
}
} else {
rename(subfile);
}
}
}
private static void copy(File src, File dest) throws Exception {
File newdir = new File(dest, src.getName());
newdir.mkdir();
File[] subFiles = src.listFiles(); // 拿到源文件夹里的文件和文件夹
for (File subfile : subFiles) {
if (subfile.isFile()) {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(subfile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(
new File(newdir, subfile.getName())));
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
bis.close();
bis.close();
} else {
copy(subfile, newdir);
}
}
}
private static File getfile() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入路径");
while (true) {
String line = sc.nextLine();
File file = new File(line);
if (!file.exists()) {
System.out.println("输入的路径是空的请重新输入");
} else if (file.isFile()) {
System.out.println("您输入的是文件路径请重新输入");
} else {
return file;
}
}
}
}
|
|