问题描述
只要我能理解java api,使用rw打开RandomAccessFile就不会在底层存储设备上同步写入错误的单字节。与rws或rwd不同。
为什么它与rw的无缓冲FileOutputStream几乎相同速度,rws/rwd速度慢10倍? / p>
以下简单代码显示了这一点,我无法得到任何合理的解释。有任何线索吗?
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
公共类StreamTest {
public static void main(String [] args)throws Exception {
OutputStream os;
RandomAccessFile raf;
int size = 10000;
文件文件=新文件(test.log);
long a = System.currentTimeMillis();
os = new FileOutputStream(file);
for(int i = 0; i< size; i ++){
os.write((1)。getBytes());
}
os.close();
long b = System.currentTimeMillis();
System.out.println(直接写作+(b-a));
raf = new RandomAccessFile(file,rws);
for(int i = 0; i< size; i ++){
raf.write((1)。getBytes());
}
raf.close();
long c = System.currentTimeMillis();
System.out.println(随机访问写入+(c-b));
raf = new RandomAccessFile(file,rw);
for(int i = 0; i< size; i ++){
raf.write((1)。getBytes());
}
raf.close();
long d = System.currentTimeMillis();
System.out.println(随机访问优化写入+(d-c));
}
}
来自,rws模式表示:
理所当然地说,强制将文件的内容写入底层设备将比其他方法慢得多,这可能允许VM / OS缓存写入。
As long as I can understand java api, opening a RandomAccessFile using "rw" does not write ervery single byte synchronously on the underlying storage device. Unlike with "rws" or "rwd".
Why is it almost the same "speed" like the unbuffered FileOutputStream with "rw" and more than 10 times slower with "rws"/"rwd"?
the following simple code shows this, and I cannot get any reasonnable explanation to this. Any clue?
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
public class StreamTest {
public static void main(String[] args) throws Exception {
OutputStream os;
RandomAccessFile raf;
int size = 10000;
File file = new File("test.log");
long a=System.currentTimeMillis();
os = new FileOutputStream(file);
for(int i=0;i<size;i++){
os.write(("1").getBytes());
}
os.close();
long b=System.currentTimeMillis();
System.out.println("writing direct "+(b-a));
raf = new RandomAccessFile(file,"rws");
for(int i=0;i<size;i++){
raf.write(("1").getBytes());
}
raf.close();
long c=System.currentTimeMillis();
System.out.println("random access write "+(c-b));
raf = new RandomAccessFile(file,"rw");
for(int i=0;i<size;i++){
raf.write(("1").getBytes());
}
raf.close();
long d=System.currentTimeMillis();
System.out.println("random access optimized write "+(d-c));
}
}
From the docs, rws mode means:
It stands to reason that forcing the file's content to be written to the underlying device would be significantly slower than the other methods, which probably allow the VM/OS to cache the writes.
这篇关于为什么java RandomAccessFile比FileOutputStream慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!