轉載參考 https://blog.csdn.net/kencolin/article/details/42246661html
1 //: net/mindview/util/TextFile.java 2 // Static functions for reading and writing text files as 3 // a single string, and treating a file as an ArrayList. 4 package net.mindview.util; 5 import java.io.*; 6 import java.util.*; 7 8 public class TextFile extends ArrayList<String> { 9 // Read a file as a single string: 10 public static String read(String fileName) { 11 StringBuilder sb = new StringBuilder(); 12 try { 13 BufferedReader in= new BufferedReader(new FileReader( 14 new File(fileName).getAbsoluteFile())); 15 try { 16 String s; 17 while((s = in.readLine()) != null) { 18 sb.append(s); 19 sb.append("\n");//???難道讀出來的不包括這一個嗎? 20 } 21 } finally { 22 in.close(); 23 } 24 } catch(IOException e) { 25 throw new RuntimeException(e); 26 } 27 return sb.toString(); 28 } 29 // Write a single file in one method call: 30 public static void write(String fileName, String text) { 31 try { 32 PrintWriter out = new PrintWriter( 33 new File(fileName).getAbsoluteFile()); 34 try { 35 out.print(text); 36 } finally { 37 out.close(); 38 } 39 } catch(IOException e) { 40 throw new RuntimeException(e); 41 } 42 } 43 // Read a file, split by any regular expression: 44 public TextFile(String fileName, String splitter) { 45 super(Arrays.asList(read(fileName).split(splitter))); 46 // Regular expression split() often leaves an empty 47 // String at the first position: 48 if(get(0).equals("")) remove(0); 49 } 50 // Normally read by lines: 51 public TextFile(String fileName) { 52 this(fileName, "\n"); 53 } 54 public void write(String fileName) { 55 try { 56 PrintWriter out = new PrintWriter( 57 new File(fileName).getAbsoluteFile()); 58 try { 59 for(String item : this) 60 out.println(item); 61 } finally { 62 out.close(); 63 } 64 } catch(IOException e) { 65 throw new RuntimeException(e); 66 } 67 } 68 // Simple test: 69 public static void main(String[] args) { 70 String file = read("TextFile.java"); 71 write("test.txt", file); 72 TextFile text = new TextFile("test.txt"); 73 text.write("test2.txt"); 74 // Break into unique sorted list of words: 75 TreeSet<String> words = new TreeSet<String>( 76 new TextFile("TextFile.java", "\\W+")); 77 // Display the capitalized words: 78 System.out.println(words.headSet("a")); 79 } 80 } /* Output: 81 [0, ArrayList, Arrays, Break, BufferedReader, BufferedWriter, Clean, Display, File, FileReader, FileWriter, IOException, Normally, Output, PrintWriter, Read, Regular, RuntimeException, Simple, Static, String, StringBuilder, System, TextFile, Tools, TreeSet, W, Write] 82 *///:~