Java to download a file from internet
There is an Online file (such as http://photo.yupoo.com/qzone1618034856/Cy3lpiGy/medish.jpg),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:
import java.net.*; import java.nio.channels.*; import java.io.*; public class download { public static void main(String[] args) {
try { URL website=new URL("http://photo.yupoo.com/qzone1618034856/Cy3lpiGy/medish.jpg"); 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:
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.Youll 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/…
Personally, Ive found Apaches HttpClient to be more than capable of everything Ive 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
!
Java File 1.基本概念 1.基本概念 File:文件和目录路径名的抽象表示形式,代表文件或者文件夹。 2.构造方法 // 根据parent抽象路径名和child路径名字符串创建一个新File实例 File(File parent, String child) /...
相关文章
- smile——Java机器学习引擎
- java 上传文件接口_Java接口实现文件上传
- java启动器_JAVA基础:Java 启动器如何查找类
- java心得体会_初学java之心得体会
- Java后台接收参数出现java.lang.Integer cannot be cast to java.lang.Double错误(已解决)[通俗易懂]
- 字符串转整型与整型转字符串的区别_java字符串转换成整数
- Java JUC
- java 数字信封_【Java密码学】使用Bouncy Castle生成数字签名、数字信封
- Java方法重载_java入门方法的使用
- Java使用echarts记录
- Java学习-如何编译适配java版本的jar包
- 最优二叉搜索树问题(Java)
- java发送邮件简单的方式
- java.net.BindException: 地址已在使用 (Bind failed)详解程序员
- Java解析XML文件详解编程语言
- Java通过在主循环中判断Boolean来停止线程详解编程语言
- 数据如何使用Java读取MySQL数据(java读取mysql)
- MySQL数据库开发实践:用 Java 开发中文应用(mysql中文java)
- 处理Redis Java: 处理过期数据的技巧(redisjava过期)
- 查询Java 操作 Redis实现有效期查询(redisjava过期)
- 使用Java实现Redis数据存储(redis集成java)
- Linux测试搭配Java快速实现稳定性验证(linux测试java)
- 秘籍学习实现纯Java版Redis(纯java版redis)
- Java桥接Oracle让数据轻松流动(java桥接oracle)
- Java快速加载Oracle数据库(java加载oracle)
- 项目Java项目中展现Redis新型性能优势(redis运用在java)