如何加快java读取文件的速度

[code="java"]FileInputStream in =???
int BUFFERLEN=1024; // 这个的设置有关系吗
byte buffer[] = new byte[BUFFERLEN];
while((c=in.read(buffer))!=-1){
for(int i=0;i<c;i++){
buffer[i]^=KEYVALUE[pos];
out.write(buffer[i]);
pos++;
if(pos==keylen) pos =0;
}
}
in.close();
out.close();[/code]

弄来一个流 。大概就是 new byte[1024] 这种方式读流。弄一个1M的文件得3,4 秒。怎么能快点

修正:8k是1k的4倍左右 :lol:

你这缓存完全没用啊。。。

这样:
[code="java"]byte[] cache = new byte[8096];
while ((length = inputStream.read(cache)) != -1) {
ops.write(cache, 0, length);
ops.flush();
}[/code]

效果都不明显的。不信,你试试。

[quote]# int BUFFERLEN=1024; // 这个的设置有关系吗 [/quote]
这个有关系的啊。你看你的代码中有这么一句:
[quote]while((c=in.read(buffer))!=-1){ [/quote]
它就是说把 in 中的数据读取部分来放至 buffer 数组中。你这个数组越大,每次读出来的数据可能就越多,读的次数也就越少。

另外,别忘了
[code="java"]out.flush();[/code]
还有,
[code="java"]
in.close();

out.close();

[/code]
这两个需要抓异常的.

如果是复制文件还可以这样:

[code="java"]public static void copy(File src, File dest) throws Exception {
if(src == null || dest == null || src.isDirectory() || dest.isDirectory()) {
throw new IllegalArgumentException();
}

    RandomAccessFile srcfile = new RandomAccessFile(src, "r");
    RandomAccessFile destfile = new RandomAccessFile(dest, "rw");

    FileChannel channel = srcfile.getChannel();
    channel.transferTo(0, channel.size(), destfile.getChannel());
    srcfile.close();
    destfile.close();
}[/code]

改变buffer的大小还是有效果的

[code="java"]public static void copy1(File src, File dest) throws Exception {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(src);
fileOutputStream = new FileOutputStream(dest);
byte[] buffer = new byte[8096];
int length = -1;
while((length = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, length);//一次性将缓冲区的所有数据都写出去
fileOutputStream.flush();
}
} finally {
if(fileInputStream != null) {
fileInputStream.close();
}
if(fileOutputStream != null) {
fileOutputStream.close();
}
}
}[/code]

[code="java"][/code]

FileWriter fw = new FileWriter("D:\"+fileName+".txt", true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write((buffer.toString()).trim());
bw.close();
fw.close();

[quote]怎么能快点 [/quote]
最快的可能就是,你把 buffer 的大小设为你文件大小或者比它更它,这样能使得每次read 的时候能读入尽可能多的字节。

参考 BufferedInputStream的默认缓冲区是8192(8K),官方说法是:再大对提升速度也没多大帮助,还要考虑内存性能。
还有就是 out.write(buffer[i]);

out最好也用BufferedOutputStream,可以优化写文件的性能

[quote]参考 BufferedInputStream的默认缓冲区是8192(8K),官方说法是:再大对提升速度也没多大帮助,还要考虑内存性能。
还有就是 out.write(buffer[i]);

out最好也用BufferedOutputStream,可以优化写文件的性能[/quote]

今天好奇,测试了一下,如果只用FileOutputStream,在我的机器上,buffer是8k左右的读写速度是1k的10倍左右,buffer在64k左右达到最佳值,性能再提高一倍左右,512k左右还有一个次优值,大致如此了。Win7 64bit/6G/jdk1.7 64bit/seagate的普通硬盘。