英文:
Fast way to read file from input stream when we know the size with low memory usage
问题
以下是翻译好的部分:
当我们知道数据的大小时,是否有更快的方法从InputStream中读取数据?我拥有的这段代码速度非常慢:
File file = new File("file.jar");
if (!file.exists()) file.createNewFile();
String url = "https://launcher.mojang.com/v1/objects/3870888a6c3d349d3771a3e9d16c9bf5e076b908/client.jar";
int len = 8461484;
InputStream is = new URL(url).openStream();
if (!file.exists())
file.createNewFile();
PrintWriter writer = new PrintWriter(file);
for (long i = 0; i < len; i++) {
writer.write(is.read());
writer.flush();
System.out.println(i);
}
writer.close();
英文:
Is there any faster way to read from an inputstream when we know the size of the data?
This code that I have is very slow:
File file = new File("file.jar");
if(!file.exists)file.createNewFile();
String url = "https://launcher.mojang.com/v1/objects/3870888a6c3d349d3771a3e9d16c9bf5e076b908/client.jar";
int len = 8461484;
InputStream is = new URL(url).openStream();
if(!file.exists())
file.createNewFile();
PrintWriter writer = new PrintWriter(file);
for(long i = 0;i < len;i ++) {
writer.write(is.read());
writer.flush();
System.out.println(i);
}
writer.close();
答案1
得分: 0
使用带有try-with-resources的缓冲输入和输出流<br>
(这确保了流在结束时都被关闭)<br>
类似这样:
try (final InputStream ist = new URL(url).openStream();
final InputStream bis = new BufferedInputStream(ist);
final OutputStream ost = new FileOutputStream(file);
final OutputStream bos = new BufferedOutputStream(ost)) {
final byte[] bytes = new byte[64_000]; // <- 尽可能大!
/**/ int count;
while ((count = bis.read(bytes)) != -1) {
bos.write(bytes, 0, count);
}
}
英文:
Use Buffered Input & Output Streams together with try-with-resources<br>
(which ensures the Streams are all closed at EOJ)<br>
Something like this:
try(final InputStream ist = new URL(url).openStream ();
final InputStream bis = new BufferedInputStream (ist);
final OutputStream ost = new FileOutputStream(file);
final OutputStream bos = new BufferedOutputStream(ost))
{
final byte[] bytes = new byte[64_000]; // <- as large as possible!
/**/ int count;
while ((count = bis.read(bytes)) != -1) {
bos.write(bytes, 0, count);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论