最快的方式写入文件? [英] Fastest way to write to file?
问题描述
我做了一个方法,它需要一个 File
和一个 String
。它用一个新的文件替换为该文件的内容。
这是我做的:
public static void Save(File file,String textToSave){
file.delete();
尝试{
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(textToSave);
out.close();
} catch(IOException e){
}
}
然而,这是痛苦的缓慢。有时需要花费一分钟的时间。
如何编写数以万计的大型文件,其中可能包含多达一百万个字符?
BufferedWriter out = new BufferedWriter(new FileWriter(file),32768);
你在运行什么样的操作系统?这也可以造成很大的不同。然而,用一个分钟来写出一个尺寸不太大的文件听起来像是一个系统问题。在Linux或其他* ix系统上,可以使用 strace
之类的东西来查看JVM是否进行了大量不必要的系统调用。 (很久以前,Java I / O很愚蠢,如果你不小心的话,会造成疯狂的低层次的 write()
系统调用,但是当我说很久以前我的意思是1998年左右。)
edit —请注意,Java程序以简单的方式编写一个简单的文件,但实际上很慢的情况本质上是一个奇怪的问题。你可以告诉CPU在文件写入过程中是否负载过重吗?它不应该是;应该几乎没有来自这样的事情的CPU负载。
I made a method that takes a File
and a String
. It replaces the file with a new file with that string as its contents.
This is what I made:
public static void Save(File file, String textToSave) {
file.delete();
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(textToSave);
out.close();
} catch (IOException e) {
}
}
However it is painfully slow. It sometimes takes over a minute.
How can I write large files with tens of thousands to maybe up to a million characters in them?
Make sure you allocate a large enough buffer:
BufferedWriter out = new BufferedWriter(new FileWriter(file), 32768);
What sort of OS are you running on? That can make a big difference too. However, taking a minute to write out a file of less-than-enormous size sounds like a system problem. On Linux or other *ix systems, you can use things like strace
to see if the JVM is making lots of unnecessary system calls. (A very long time ago, Java I/O was pretty dumb and would make insane numbers of low-level write()
system calls if you weren't careful, but when I say "a long time ago" I mean 1998 or so.)
edit — note that the situation of a Java program writing a simple file in a simple way, and yet being really slow, is an inherently odd one. Can you tell if the CPU is heavily loaded while the file is being written? It shouldn't be; there should be almost no CPU load from such a thing.
这篇关于最快的方式写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!