如何使用 Java 从 Internet 下载和保存文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/921262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to download and save a file from Internet using Java?
提问by echoblaze
There is an online file (such as http://www.example.com/information.asp
) I need to grab and save to a directory. I know there are several methods for grabbing and reading online files (URLs) line-by-line, but is there a way to just download and save the file using Java?
有一个在线文件(例如http://www.example.com/information.asp
)我需要抓取并保存到一个目录中。我知道有几种方法可以逐行抓取和读取在线文件 (URL),但是有没有一种方法可以使用 Java 下载和保存文件?
采纳答案by dfa
Give Java NIOa try:
提供的Java NIO一试:
URL website = new URL("http://www.website.com/information.asp");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("information.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
Using transferFrom()
is potentiallymuch more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.
使用transferFrom()
是可能不是一个简单的循环从源信道的读取和写入这个频道有效得多。许多操作系统可以将字节直接从源通道传输到文件系统缓存中,而无需实际复制它们。
Check more about it here.
在此处查看更多相关信息。
Note: The third parameter in transferFrom is the maximum number of bytes to transfer. Integer.MAX_VALUE
will transfer at most 2^31 bytes, Long.MAX_VALUE
will allow at most 2^63 bytes (larger than any file in existence).
注意: transferFrom 中的第三个参数是要传输的最大字节数。 Integer.MAX_VALUE
最多传输 2^31 个字节,Long.MAX_VALUE
最多允许传输2^63 个字节(比现有的任何文件都大)。
回答by z -
Downloading a file requires you to read it, either way you will have to go through the file in some way. Instead of line by line, you can just read it by bytes from the stream:
下载文件需要您阅读它,无论哪种方式,您都必须以某种方式浏览文件。您可以从流中按字节读取,而不是逐行读取:
BufferedInputStream in = new BufferedInputStream(new URL("http://www.website.com/information.asp").openStream())
byte data[] = new byte[1024];
int count;
while((count = in.read(data,0,1024)) != -1)
{
out.write(data, 0, count);
}
回答by Ben Noland
public void saveUrl(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
}
You'll need to handle exceptions, probably external to this method.
您需要处理异常,可能在此方法之外。
回答by belgariontheking
Personally, I've found Apache's HttpClientto be more than capable of everything I've needed to do with regards to this. Hereis a great tutorial on using HttpClient
就我个人而言,我发现Apache 的 HttpClient能够胜任我需要做的所有事情。 这是一个关于使用 HttpClient 的很棒的教程
回答by u290629
Use apache commons-io, just one line code:
使用 apache commons-io,只需一行代码:
FileUtils.copyURLToFile(URL, File)
回答by mumair
import java.io.*;
import java.net.*;
public class filedown {
public static void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
URL url = new URL(address);
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
numWritten += numRead;
}
System.out.println(localFileName + "\t" + numWritten);
}
catch (Exception exception) {
exception.printStackTrace();
}
finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
catch (IOException ioe) {
}
}
}
public static void download(String address) {
int lastSlashIndex = address.lastIndexOf('/');
if (lastSlashIndex >= 0 &&
lastSlashIndex < address.length() - 1) {
download(address, (new URL(address)).getFile());
}
else {
System.err.println("Could not figure out local file name for "+address);
}
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
download(args[i]);
}
}
}
回答by xuesheng
Simpler nio usage:
更简单的 nio 用法:
URL website = new URL("http://www.website.com/information.asp");
try (InputStream in = website.openStream()) {
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
}
回答by oktieh
There is an issue with simple usage of:
简单使用有一个问题:
org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
if you need to download and save very large files, or in general if you need automatic retries in case connection is dropped.
如果您需要下载和保存非常大的文件,或者一般情况下如果您需要在连接断开时自动重试。
What I suggest in such cases is Apache HttpClient along with org.apache.commons.io.FileUtils. For example:
在这种情况下,我建议使用 Apache HttpClient 和 org.apache.commons.io.FileUtils。例如:
GetMethod method = new GetMethod(resource_url);
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
logger.error("Get method failed: " + method.getStatusLine());
}
org.apache.commons.io.FileUtils.copyInputStreamToFile(
method.getResponseBodyAsStream(), new File(resource_file));
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
回答by Brian Risk
This answer is almost exactly like selected answer but with two enhancements: it's a method and it closes out the FileOutputStream object:
这个答案几乎与选择的答案完全一样,但有两个增强:它是一个方法,它关闭了 FileOutputStream 对象:
public static void downloadFileFromURL(String urlString, File destination) {
try {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
回答by BullyWiiPlaza
When using Java 7+
use the following method to download a file from the Internet and save it to some directory:
当使用Java 7+
使用下面的方法来从Internet下载文件并将其保存到某个目录:
private static Path download(String sourceURL, String targetDirectory) throws IOException
{
URL url = new URL(sourceURL);
String fileName = sourceURL.substring(sourceURL.lastIndexOf('/') + 1, sourceURL.length());
Path targetPath = new File(targetDirectory + File.separator + fileName).toPath();
Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
return targetPath;
}
Documentation here.
文档在这里。