当我们知道内存使用率低的大小时,从输入流读取文件的快速方法

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

当我们知道数据大小时,有没有更快的方法从输入流中读取? 我的这段代码非常慢:

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();

将缓冲输入和输出流与 try-with-resources 一起使用
(确保流在 EOJ 处全部关闭)
像这样:

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);
    }
}