用Java将一文件夹下所有文本文件统一写入到一个文本文件中
1 /** 2 * 3 */ 4 package com.kk.test; 5 6 import java.io.*; 7 import java.util.*; 8 9 /** 10 * @author Admin 11 * 12 */ 13 public class ReadTxts2OneTxt { 14 15 public static final String encoding = "gbk"; 16 17 /** 18 * @param args 19 */ 20 public static void main(String[] args) { 21 22 23 File dir = new File("E:\\"); 24 ArrayList<File> allTxtFiles = new ArrayList<File>(); 25 getAlltxtFiles(dir, allTxtFiles); 26 27 File destFile = new File("C:\\Users\\Admin\\Desktop\\all.txt"); 28 29 for (File srcFile : allTxtFiles) { 30 ArrayList<String> lines = new ArrayList<String>(); 31 readTxt(srcFile, lines); 32 save(destFile, lines); 33 } 34 35 36 } 37 38 public static void readTxt(File file, ArrayList<String> lines) { 39 40 FileInputStream fis = null; 41 InputStreamReader sr = null; 42 BufferedReader br = null; 43 try { 44 fis = new FileInputStream(file); 45 sr = new InputStreamReader(fis,encoding); 46 br = new BufferedReader(sr); 47 String line = null; 48 while ((line = br.readLine()) != null) { 49 lines.add(line + System.getProperty("line.separator")); 50 } 51 } catch (FileNotFoundException e) { 52 e.printStackTrace(); 53 } catch (IOException e) { 54 e.printStackTrace(); 55 } finally { 56 if (br != null) { 57 try { 58 br.close(); 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 } 63 if (sr != null) { 64 try { 65 sr.close(); 66 } catch (IOException e) { 67 e.printStackTrace(); 68 } 69 } 70 if (fis != null) { 71 try { 72 fis.close(); 73 } catch (IOException e) { 74 e.printStackTrace(); 75 } 76 } 77 }// finally 78 } 79 80 /** 81 * @param line 82 */ 83 public static void save(File file, ArrayList<String> lines) { 84 85 FileOutputStream fos = null; 86 OutputStreamWriter sw = null; 87 BufferedWriter bw = null; 88 try { 89 fos = new FileOutputStream(file, true); 90 sw = new OutputStreamWriter(fos,encoding); 91 bw = new BufferedWriter(sw); 92 for (String line : lines) { 93 bw.write(line); 94 } 95 } catch (Exception e) { 96 e.printStackTrace(); 97 } finally { 98 if (bw != null) { 99 try { 100 bw.close(); 101 } catch (IOException e) { 102 e.printStackTrace(); 103 } 104 } 105 if (sw != null) { 106 try { 107 sw.close(); 108 } catch (IOException e) { 109 e.printStackTrace(); 110 } 111 } 112 if (fos != null) { 113 try { 114 fos.close(); 115 } catch (IOException e) { 116 e.printStackTrace(); 117 } 118 } 119 }// finally 120 } 121 122 public static ArrayList<File> getAlltxtFiles(File dir, ArrayList<File> txtFiles) { 123 File[] files = dir.listFiles(); 124 for (File file : files) { 125 if (file.isDirectory()) { 126 getAlltxtFiles(file,txtFiles); 127 } else if (file.getName().endsWith(".java") || file.getName().endsWith(".jsp")) { 128 txtFiles.add(file); 129 System.out.println(file.getName()); 130 } 131 } 132 return txtFiles; 133 } 134 135 }
本文来自博客园,作者:Krise,转载请注明原文链接:https://www.cnblogs.com/krise/articles/12034963.html
浙公网安备 33010602011771号