下边展示了一个读写文件的工具类, 通过继承arrayList将文件逐行读入内存并保存的实现也值得借鉴, 当然, 在实际使用中还要考虑性能和实用性.
package com.cnsuning.file;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
public class TextFile extends ArrayList<String> {
public TextFile(String fileName){
this(fileName,"\n");
//split分割经常会产生空白, 尝试删除
if(get(0).equals("")){
remove(0);
}
}
public TextFile(String fileName, String split) {
super(Arrays.asList(read(fileName).split(split)));
}
public static String read(String fileName) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
try {
String line;
while (null != (line = reader.readLine())) {
sb.append(line);
sb.append("\n");
}
} finally {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static void write(String fileName, String text) {
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter(fileName)));
try {
writer.print(text);
} finally {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(String fileName){
try {
PrintWriter writer = new PrintWriter(fileName);
for(String line: this){
writer.println(line);
}
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
TextFile text = new TextFile("D:\\work\\会员账户管理\\sales_svn.txt");
StringBuilder sb = new StringBuilder();
int lineNum = 1;
for(String line: text){
sb.append(lineNum);
sb.append(": ");
sb.append(line);
sb.append("\n");
lineNum++;
}
TextFile.write("D:\\test.txt", sb.toString());
System.out.println(TextFile.read("D:\\work\\会员账户管理\\sales_svn.txt"));
System.out.println(TextFile.read("D:\\test.txt"));
}
}