- public class Test09 {
- public static void main(String[] args) {
- ArrayList<File> arrList = new ArrayList<File>();
- //源文件躲在路径
- File file = new File("E:\\StudyFile");
- fileToList(file, arrList);
- writeToFile(arrList);
- }
- //把源文件后缀是.java的文件写到List集合内
- public static void fileToList(File dir, List<File> list) {
- File[] files = dir.listFiles();
- for (File file : files) {
- if (file.isDirectory()) {
- fileToList(file, list);
- } else {
- if (file.getName().endsWith(".java")) {
- list.add(file);
- }
- }
- }
- }
- //把List集合内的文件写到目的文件夹e:\\targetFile
- public static void writeToFile(List<File> list) {
- File targetFile = new File("e:\\targetFile");
- // 不存在则创建新目录
- if (!targetFile.exists()) {
- targetFile.mkdir();
- }
- BufferedReader bur = null;
- BufferedWriter buw = null;
- String s;
- for (File file : list) {
- try {
- bur = new BufferedReader(new InputStreamReader(
- new FileInputStream(file)));
- // 后缀名替换
- String targetFileName = file.getName().replaceAll(".java",".txt");
- buw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(targetFile,targetFileName))));
- while ((s = bur.readLine()) != null) {
- buw.write(s);
- buw.newLine();
- buw.flush();
- }
- } catch (Exception e) {
- System.out.println("写入目的文件失败!!!");
- }
- try {
- bur.close();
- buw.close();
- } catch (IOException e) {
- System.out.println("关闭流失败!!");
- }
- }
- System.out.println("复制成功!");
- }
- }
复制代码
|
|