import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;
public class TextFile extends ArrayList<String> {
private static final long serialVersionUID = 2198370200846025857L;
/**
* 读文件输出为字符串
*/
public static String read(String fileName) {
StringBuffer sb = new StringBuffer();
try {
File absoFile = new File(fileName).getAbsoluteFile();
BufferedReader br = new BufferedReader(new FileReader(absoFile));
try {
String s = null;
while ((s = br.readLine()) != null) {
sb.append(s).append("\n");
}
} finally {
if (br != null) {
br.close();
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
/**
* 向文件中写入文本
*/
public static void write(String fileName, String text){
File abFile = new File(fileName).getAbsoluteFile();
try {
PrintWriter writer = new PrintWriter(abFile);
try {
writer.print(text);
} finally {
writer.close();
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public TextFile(String fileName, String splitter){
super(Arrays.asList(read(fileName).split(splitter)));
//split后常留下一个空
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 (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
System.out.print(read("d:\\a.txt"));
write("d:\\a.txt","This is not the end of the file.");
System.out.print(read("d:\\a.txt"));
TreeSet<String> words = new TreeSet<String>(new TextFile("d:\\a.txt","\\W+"));
//打印首字母大写的单词
System.out.println(words.headSet("a"));
}
}
08-24
08-24