当我们知道数据大小时,有没有更快的方法可以从输入流中读取?我的这段代码非常慢:
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);
}
}