Fast way to read file from input stream when we know the size with low memory usage

huangapple 未分类评论61阅读模式
标题翻译

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(&quot;file.jar&quot;);

if(!file.exists)file.createNewFile();
String url = &quot;https://launcher.mojang.com/v1/objects/3870888a6c3d349d3771a3e9d16c9bf5e076b908/client.jar&quot;;
int len = 8461484;

InputStream is = new URL(url).openStream();
	
if(!file.exists())
	file.createNewFile();

PrintWriter writer = new PrintWriter(file);

for(long i = 0;i &lt; 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]; // &lt;- 尽可能大!
    /**/  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]; // &lt;- as large as possible!
	/**/  int    count;

	while ((count = bis.read(bytes)) != -1) {
		bos.write(bytes, 0, count);
	}
}

huangapple
  • 本文由 发表于 2020年3月4日 05:31:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/60515829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定