This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
The problem
Has an online file (for example, http://www.example.com/information.asp), I want to grab and saved in the directory. I know there are several ways to capture and read online files (URLs) line by line, but is there a way to download and save files in Java?
answer
Answer 1
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);
Copy the code
Using transferFrom() may perform better than a simple loop read. Many operating systems can transfer bytes directly from the source channel to the file system cache without actually copying them.
See here for more information about FileChannel.
Note: The third parameter in transferFrom is the maximum number of bytes transferred. Integer.MAX_VALUE will transfer up to 2^31 bytes, and long. MAX_VALUE will allow up to 2^63 bytes (in practice many files are larger than this).
Answer 2
With Apache Commons-io, this can be done with just one line of code:
FileUtils.copyURLToFile(URL, File)
Copy the code
Answer 3
NIO is simpler:
URL website = new URL("http://www.website.com/information.asp");
try (InputStream in = website.openStream()) {
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
}
Copy the code
Answer 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(); }}}Copy the code
Translation content sources Stack Overflow:stackoverflow.com/questions/9…