gpt4 book ai didi

java - 这是用 Java 下载文件的最佳方式吗?

转载 作者:行者123 更新时间:2023-11-30 06:36:35 25 4
gpt4 key购买 nike

public void download(String url, String destination) {
BufferedOutputStream localBufferedOutputStream = null;
URLConnection localURLConnection = null;
InputStream localInputStream = null;
try {
URL localURL = new URL(url);

localBufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destination));
localURLConnection = localURL.openConnection();
localInputStream = localURLConnection.getInputStream();

byte[] arrayOfByte = new byte[1024];
int i;
while ((i = localInputStream.read(arrayOfByte)) != -1) {
localBufferedOutputStream.write(arrayOfByte, 0, i);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (localInputStream != null) {
localInputStream.close();
}
if (localBufferedOutputStream != null) {
localBufferedOutputStream.close();
}
} catch (IOException localIOException3) {
System.out.println(localIOException3);
}
}
}

我正在调试我的应用程序,它似乎有点慢。我想知道这是不是我的互联网。这是用java下载文件的正确方法吗?文件大小为 26mb。

最佳答案

您应该始终关注 Apache 等库。他们为您完成了所有艰苦的工作: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html

我用

static String   readFileToString(File file)
Reads the contents of a file into a String using the default encoding for the VM.

很多。

如果您知道自己有一个 URL(因此流式传输),请查看: http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html

关于java - 这是用 Java 下载文件的最佳方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4697226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com