黑马程序员笔记:编写程序实现指定文件的复制粘贴

来源:互联网 发布:独立域名什么意思 编辑:程序博客网 时间:2024/05/16 19:46
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;


public class Test9 {


/**

* 编写程序, 将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub


// 创建Scanner对象接收键盘输入源路径和目标路径
Scanner scanner = new Scanner(System.in);
// 提示输入源路径
System.out.println("请输入源路径:");
String sourcePath = scanner.nextLine();
// 提示输入目标路径
System.out.println("请输入目标路径:");
String targetPath = scanner.nextLine();
// 获取源路径
File source = new File(sourcePath);
// 判断源路径是否存在,如果不存在,报错并返回
if (!source.exists()) {
System.out.println("该源路径不存在");
return;
}
// 获取目标路径
File target = new File(targetPath);
// 判断目标路径是否存在,如果不存在则创建该路径
if (!target.exists()) {
target.mkdirs();
}


// 调用拷贝方法
copyAllJava(source, target);
System.out.println("拷贝成功");
}


private static void copyAllJava(File source, File target)
throws IOException {
// TODO Auto-generated method stub
// 获取源路径中的所有文件
File[] sourceFileList = source.listFiles();
// 遍历所有文件
for (int i = 0; i < sourceFileList.length; i++) {
// 如果文件是*.java文件,则复制到目标路径,并该为*.txt文件
if (sourceFileList[i].getName().endsWith(".java")) {
File targetFile = new File(target, sourceFileList[i].getName().replace(
".java", ".txt"));
BufferedReader bufReader = null;
BufferedWriter bufWriter = null;
try {
bufReader = new BufferedReader(new FileReader(sourceFileList[i]));
bufWriter = new BufferedWriter(new FileWriter(targetFile));
String str = "";
while ((str = bufReader.readLine()) != null) {// 运用字符缓冲流,复制java文件进入目标路径下同名txt文件.
bufWriter.write(str);
bufWriter.newLine();
}
} catch (IOException e) {
throw e;
} finally {// 关闭资源.
if (bufWriter != null)
try {
bufWriter.close();
} catch (IOException e) {
throw e;
} finally {
if (bufReader != null)
try {
bufReader.close();
} catch (IOException e) {
throw e;
}
}
}
}
// 如果文件是文件夹,则采用递归方法遍历该文件夹
if (sourceFileList[i].isDirectory()) {
File targetFiles = new File(target, sourceFileList[i].getName());
targetFiles.mkdirs();
copyAllJava(sourceFileList[i], targetFiles);
}
}


}


}
0 0
原创粉丝点击