File file = new File(directory + ".zip");
if(file.exists()) {
return;
}
url = new URL("http://someURL" + session);
is = url.openStream();
fos = new FileOutputStream(file);
int data;
//Leser forbi det første tegnet
is.read();
while ((data = is.read()) != -1) {
fos.write(data);
}
is.close();
fos.close();
当我调用此方法时,我的程序冻结了20。如何更快地完成这个过程?
答案 0 :(得分:8)
使用缓冲区一次传输一小段数据,而不是一次读取一个字节。这对于大文件来说将更加节省资源。我想你的zip文件很大。
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = is.read(buffer))) {
fos.write(buffer, 0, n);
}
答案 1 :(得分:0)
您可以使用FileChannel
和ByteBuffer
来提高效果。特别是ByteBuffer
的大小将起到魔力。
FileInputStream fin = new FileInputStream(infile);
ByteBuffer buffer = ByteBuffer.allocate(1024);
FileChannel fcin = fin.getChannel();
fcin.read(buffer);
如果您要从一个复制到另一个,可以直接使用
fileChannel.transferFrom(ReadableByteChannel src, long position, long count)
这非常快,因为不会将内容复制到用户空间。请参阅here。
ByteBuffer.allocateDirect(1024)
代替ByteBuffer.allocate(1024)
。 此方法返回的缓冲区通常具有比非直接缓冲区更高的分配和解除分配成本。直接缓冲区的内容可能位于正常的垃圾收集堆之外,因此它们对应用程序的内存占用量的影响可能并不明显。因此,建议直接缓冲区主要分配给受基础系统本机I / O操作影响的大型长期缓冲区。通常,最好只在它们在程序性能中产生可测量的增益时分配直接缓冲区。 source
答案 2 :(得分:-1)
您不能让它更快,但您可以使用Java NIO API阻止它阻止。这将允许程序在后台下载文件时将控制权传回给线程。