【发布时间】:2014-08-10 01:09:11
【问题描述】:
我正在为我的项目开发更新程序,我想快速下载文件。 每次更新,都会有一些文件大小不同。所以我认为我不需要缓冲区,或者肯定没有定义。我已经这么写了:
File file = new File..
InputStream input = new InputStream...
OutputStream output = new OutputStream(..).write(input.read());
这个运行完美!但我的朋友对我说; “嘿,我们从 jdk7 获得了 FileChannel”。 然后我考虑了一下,但是我们不能在没有 ByteBuffer 的情况下创建和导入数据到 FileChannel。
FileChannel channel = new FileOutputStream(file).getChannel();
ByteBuffer buffer = ByteBuffer.allocateDirect(..);
buffer.putInt(inputstream.read());
channel.write(buffer);
那么更快的是什么?更好的 ?谢谢!
更新:(我认为最好的解决方案,非常快)
URLConnection connection = new URL(url).openConnection();
File file = new File(connection.getURL().getPath().substring(1));
if (file.getParentFile() != null)
file.getParentFile().mkdirs();
FileChannel output = new FileOutputStream(file).getChannel();
output.transferFrom(Channels.newChannel(connection.getInputStream()), 0, connection.getContentLengthLong());
有效!
【问题讨论】:
-
它适用于您尝试过的东西。一般来说,transferFrom/To() 不能保证在一次调用中完成整个传输。这就是他们返回计数的原因。你必须循环。
-
为什么?没有解释
-
新:我尝试下载 2GB,它确实有效!下载没有中断
-
如何在控制器中使用它来响应?