编写程序实现指定文件的复制粘贴

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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值