这是在java中下载文件的最佳方式吗? [英] Is this the best way to download a file in java?
问题描述
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。
I'm debugging my application and it seems a bit slow. I'm wondering if it's my internet. Is this the proper way to download a file in java? The file is 26mb.
推荐答案
您应该始终关注像Apache这样的库。他们为你做了所有辛苦的工作:
http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
You should always look to libraries such as Apache. They have done all the hard work for you: 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
If you know you have a URL (and so stream) look at: http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html
这篇关于这是在java中下载文件的最佳方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!