Java mindview_net.mindview.util.TextFile 类 java编程思想

1 //: net/mindview/util/TextFile.java2 //Static functions for reading and writing text files as3 //a single string, and treating a file as an ArrayList.

4 packagenet.mindview.util;5 import java.io.*;6 import java.util.*;7

8 public class TextFile extends ArrayList{9 //Read a file as a single string:

10 public staticString read(String fileName) {11 StringBuilder sb = newStringBuilder();12 try{13 BufferedReader in= new BufferedReader(newFileReader(14 newFile(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 newRuntimeException(e);26 }27 returnsb.toString();28 }29 //Write a single file in one method call:

30 public static voidwrite(String fileName, String text) {31 try{32 PrintWriter out = newPrintWriter(33 newFile(fileName).getAbsoluteFile());34 try{35 out.print(text);36 } finally{37 out.close();38 }39 } catch(IOException e) {40 throw newRuntimeException(e);41 }42 }43 //Read a file, split by any regular expression:

44 publicTextFile(String fileName, String splitter) {45 super(Arrays.asList(read(fileName).split(splitter)));46 //Regular expression split() often leaves an empty47 //String at the first position:

48 if(get(0).equals("")) remove(0);49 }50 //Normally read by lines:

51 publicTextFile(String fileName) {52 this(fileName, "\n");53 }54 public voidwrite(String fileName) {55 try{56 PrintWriter out = newPrintWriter(57 newFile(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 newRuntimeException(e);66 }67 }68 //Simple test:

69 public static voidmain(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 words = new TreeSet(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 *///:~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值