本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看<活动链接>
问题
有一个在线文件(例如,http://www.example.com/information.asp),我想要抓取并保存到目录中。我知道有几种逐行捕获和读取在线文件(URLs)的方法,但是有没有一种方法通过 Java 来实现下载和保存文件?
回答
回答1
尝试 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);
使用 transferFrom() 可能比简单的循环读取性能更高。许多操作系统可以将字节直接从源通道直接传输到文件系统缓存中,而无需实际复制它们。
关于 FileChannel 更多信息查看这里。
注意:transferFrom 中的第三个参数是传输的最大字节数。 Integer.MAX_VALUE 将最多传输 2^31 个字节,Long.MAX_VALUE 最多允许2^63 个字节(在实际中许多文件都比这大)。
回答2
使用 apache commons-io,仅仅一行代码就可实现:
FileUtils.copyURLToFile(URL, File)
回答3
NIO 方式更简单:
URL website = new URL("http://www.website.com/information.asp");
try (InputStream in = website.openStream()) {
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
}
回答4
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();
}
}
}
翻译内容来源Stack Overflow:stackoverflow.com/questions/9…