TextFile 作为自写的方法,继承自List<String>。像统计文本中出现的哪些单词,不重复等等,适合用Set集合完成统计。
class TextFile extends ArrayList<String>{
public static String read(String filename){
StringBuilder sb=new StringBuilder();
try{
BufferedReader in=new BufferedReader(new FileReader(
new File(filename).getAbsoluteFile()));
try{
String s;
while((s=in.readLine())!=null){
sb.append(s);
sb.append("\n");
}
}finally{
in.close();
}
}catch(IOException e){
throw new RuntimeException(e);
}
return sb.toString();
}
public TextFile(String filename,String splitter){
super(Arrays.asList(read(filename).split(splitter)));
if(get(0).equals("")) remove(0);
}
public TextFile(String filename){
this(filename,"\n");
}
public void write(String filename){
try{
PrintWriter out=new PrintWriter(new File
(filename).getAbsoluteFile());
try{
for(String item : this) out.println(item);
}finally{
out.close();
}
}catch(IOException e){
throw new RuntimeException(e);
} }
public static void write(String filename,String text){
// 其中filename指明要写入的文件名,text指明写入的字符串内容
try{
FileWriter fwriter=new FileWriter(new File
(filename).getAbsoluteFile());
BufferedWriter out=new BufferedWriter(fwriter);
String []tx=text.split("\n");
try{
for(int i=0;i<tx.length;i++)
{
out.write(tx[i]);
out.newLine();
}
}finally{
out.flush();
out.close();
}
}catch(IOException e){
throw new RuntimeException(e); } }
}
public static void main(String[] args) {
Set<String> words = new TreeSet<String>(
new TextFile("StatckTest.java","\\W+"));
System.out.print(words);
System.out.println(words.size()); Set<String> words2 = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
words2.addAll(words);
System.out.print(words2);
System.err.println(words2.size()); //这里有什么不同的? }