Java to download a file from internet
There is an Online file (such as https://res.3425.com.cn/aliyunqi/ah2c3kquvoy.gif),as below:
If you wan to download this picture,how can we grap and save to a directory?
ok,here have some ways as below:
The first way
using the Java NIO,here is the main code snippet:
import java.net.*; import java.nio.channels.*; import java.io.*; public class download { public static void main(String[] args) { try { URL website=new URL("https://res.3425.com.cn/aliyunqi/ah2c3kquvoy.gif"); ReadableByteChannel rbc=Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream("C://information.html"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Using transferFrom()
is potentially much
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.
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).
Build and run! Very cool, the result as below:
The seconed way:
use apache commons-io,just one line code,as below:
org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
Take note that
copyURLToFile
with
timeout parameter is only available since version 2.0 of Commons IO library. See Java
docs
The Third way:
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:
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, address.substring(lastSlashIndex + 1)); } 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]); } } }
If
in.close
throws
an exception, out.close
is
not called.You'll need to handle exceptions, probably external to this method. Using
a BufferedInputStream
can
sometimes lead to SocketTimeoutException being thrown. Replace it byInputStream
and
you should be ok. Here are some background details:stackoverflow.com/questions/2964044/…
Finally:
Personally, I've found Apache's HttpClient to be more than capable of everything I've needed to do with regards to this. Here is a great tutorial on using HttpClient. Hope this post can help you!
Last But no Least:if you have any issues,you can check my blog,thinks your attention
!
最後更新:2017-04-03 12:53:59
上一篇:
linux驅動開發--內核鏈表
下一篇:
Beanstalkd隊列 概述
Linux係統小技巧(4):環境變量JAVA_TOOL_OPTIONS簡介
Socket PrintWriter 中 write() 與 print() 的區別
解析紅外探測器的光學讀出結構工業設計方法
創業者談360路由失敗:懶惰和自以為是的產品設計
《深入理解Elasticsearch(原書第2版)》一2.4 過濾器的使用及作用原理
Debug與Release的區別
Grizzly——不走尋常路的nio框架
怡海軟件:2017年企業級SaaS服務發展5大趨勢
阿裏雲將新增印度和印尼數據中心 加速全球化布局
Ring.velocity:render velocity templates for ring in clojure