有没有大文件频繁读写操作的方法呢???效率越高越好
文件在1M-10M 按10K的速度增加
我这的方法需要5分钟左右的时间才能完成
求个效率高的文件读写方法(TXT文件)
下面是我的垃圾方法 //保存txt
public static void Savetxt(String file, String txt) {
String s = new String();
String s1 = new String();
txt=txt.replace("<br />", "\r\n");
txt=txt.replace(" ", " ");
txt=txt.replace(" ", " ");
try {
File f = new File(file);
if (f.exists()) {
} else {
if (f.createNewFile()) {
}
}
BufferedReader input = new BufferedReader(new FileReader(f)); while ((s = input.readLine()) != null) {
s1 += s + "\r\n";
}
input.close();
s1 += txt; BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(s1);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
文件在1M-10M 按10K的速度增加
我这的方法需要5分钟左右的时间才能完成
求个效率高的文件读写方法(TXT文件)
下面是我的垃圾方法 //保存txt
public static void Savetxt(String file, String txt) {
String s = new String();
String s1 = new String();
txt=txt.replace("<br />", "\r\n");
txt=txt.replace(" ", " ");
txt=txt.replace(" ", " ");
try {
File f = new File(file);
if (f.exists()) {
} else {
if (f.createNewFile()) {
}
}
BufferedReader input = new BufferedReader(new FileReader(f)); while ((s = input.readLine()) != null) {
s1 += s + "\r\n";
}
input.close();
s1 += txt; BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(s1);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
FileChannel in=new FileInputStream(new File("filename1")).getChannel(),
out=new FileOutputStream(new File("filename2")).getChannel();
in.transferTo(0,in.size(),out);
txt=txt.replace(" ", " ");
txt=txt.replace(" ", " ");这个改了,用chatat,只遍历一次,正则表达式是很慢的。
上面代码意思就是,构造了两个文件管道,从in传递给out。非常简单。
FileChanel fc = new RandomAccessFile("a.txt","rw").getChanel();
fc.position(fc.size);
fc.write(ByteBuffer.wrap(txt).getBytes("utf-8"));
fc.close();
have a try
http://www.jdon.com/concurrent/nio%D4%AD%C0%ED%D3%A6%D3%C3.htm
这样的话,就不需要在读取原来的文件。只需要以追加的方式来写入文件就可以了。楼主可以把Reader相关的代码省略了。
在创建FileWriter的时候,应该有很多构造器可以选用。
比如:boolean append = true;
BufferedWriter output = new BufferedWriter(new FileWriter(f,append));具体是什么,要楼主自己查看一下API。我印象中是这个构造器。
o(∩_∩)o...
在文本内容后面直接追加新内容
比你的那个 s1 += txt 效率高多了