根据url从网络上下载资源

第一种写法:

 
 
  1. package com.ifp.business.test;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. public class TestMethod {
  10. /**
  11. * 从网络Url中下载文件
  12. *
  13. * @param urlStr
  14. * @param fileName
  15. * @param savePath
  16. * @throws IOException
  17. */
  18. public static void downLoadFromUrl(String urlStr, String fileName,
  19. String savePath) throws IOException {
  20. System.out.println(urlStr);
  21. URL url = new URL(urlStr);
  22. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  23. // 设置超时间为3秒
  24. conn.setConnectTimeout(3 * 1000);
  25. // 防止屏蔽程序抓取而返回403错误
  26. conn.setRequestProperty("User-Agent",
  27. "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  28. // 设定请求的方法,默认是GET 这里不能使用post提交
  29. conn.setRequestMethod("GET");
  30. // 设置字符编码
  31. conn.setRequestProperty("Charset", "UTF-8");
  32. // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
  33. conn.connect();
  34. // 文件大小
  35. int fileLength = conn.getContentLength();
  36. // 得到输入流
  37. InputStream inputStream = conn.getInputStream();
  38. // 获取自己数组
  39. byte[] getData = readInputStream(inputStream, fileLength);
  40. // 文件保存位置
  41. File saveDir = new File(savePath);
  42. if (!saveDir.exists()) {
  43. saveDir.mkdir();
  44. }
  45. File file = new File(saveDir + File.separator + fileName);
  46. FileOutputStream fos = new FileOutputStream(file);
  47. fos.write(getData);
  48. if (fos != null) {
  49. fos.close();
  50. }
  51. if (inputStream != null) {
  52. inputStream.close();
  53. }
  54. System.out.println("info:" + url + " download success");
  55. }
  56. /**
  57. * 从输入流中获取字节数组
  58. *
  59. * @param inputStream
  60. * @return
  61. * @throws IOException
  62. */
  63. public static byte[] readInputStream(InputStream inputStream, int fileLength)
  64. throws IOException {
  65. byte[] buffer = new byte[1024];
  66. int len = 0;
  67. int size = 0;
  68. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  69. while ((len = inputStream.read(buffer)) != -1) {
  70. size += len;
  71. bos.write(buffer, 0, len);
  72. //打印下载的百分比
  73. System.out
  74. .println("下载了-------> " + size * 100 / fileLength + "%\n");
  75. }
  76. bos.close();
  77. return bos.toByteArray();
  78. }
  79. public static void main(String[] args) {
  80. try {
  81. downLoadFromUrl(
  82. "http://imgbbs.heiguang.net/forum/201510/06/104432cjc7c8tx7xxqqkgq.jpg",
  83. "百度.jpg", "d:/111111/");
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. }
  87. }
  88. }

第二种写法:

 
 
  1. package test.downFile;
  2. import java.io.BufferedInputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.OutputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.net.URLConnection;
  11. import java.net.URLEncoder;
  12. //测试下载的类
  13. public class DownFile {
  14. public static void main(String[] args) {
  15. downloadFile(
  16. "http://imgbbs.heiguang.net/forum/201510/06/104432cjc7c8tx7xxqqkgq.jpg",
  17. "d:/111111/");
  18. }
  19. /**
  20. * Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,
  21. * 但不够简便;
  22. *
  23. * 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求
  24. * 4.以输入流的形式获取返回内容 5.关闭输入流
  25. *
  26. */
  27. /**
  28. *
  29. * @param urlPath
  30. * 下载路径
  31. * @param downloadDir
  32. * 下载存放目录
  33. * @return 返回下载文件
  34. */
  35. public static File downloadFile(String urlPath, String downloadDir) {
  36. File file = null;
  37. try {
  38. // 统一资源
  39. URL url = new URL(urlPath);
  40. // 连接类的父类,抽象类
  41. URLConnection urlConnection = url.openConnection();
  42. // 设置超时间为3秒
  43. urlConnection.setConnectTimeout(3 * 1000);
  44. // 防止屏蔽程序抓取而返回403错误
  45. urlConnection.setRequestProperty("User-Agent",
  46. "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  47. // http的连接类
  48. HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
  49. // 设定请求的方法,默认是GET
  50. httpURLConnection.setRequestMethod("GET");
  51. // 设置字符编码
  52. httpURLConnection.setRequestProperty("Charset", "UTF-8");
  53. // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
  54. httpURLConnection.connect();
  55. // 文件大小
  56. int fileLength = httpURLConnection.getContentLength();
  57. // 文件名
  58. String filePathUrl = httpURLConnection.getURL().getFile();
  59. String fileFullName = filePathUrl.substring(filePathUrl
  60. .lastIndexOf(File.separatorChar) + 1);
  61. System.out.println("file length---->" + fileLength);
  62. URLConnection con = url.openConnection();
  63. BufferedInputStream bin = new BufferedInputStream(
  64. httpURLConnection.getInputStream());
  65. String path = downloadDir + File.separatorChar + fileFullName;
  66. file = new File(path);
  67. if (!file.getParentFile().exists()) {
  68. file.getParentFile().mkdirs();
  69. }
  70. OutputStream out = new FileOutputStream(file);
  71. int size = 0;
  72. int len = 0;
  73. byte[] buf = new byte[1024];
  74. while ((size = bin.read(buf)) != -1) {
  75. len += size;
  76. out.write(buf, 0, size);
  77. // 打印下载百分比
  78. System.out.println("下载了-------> " + len * 100 / fileLength
  79. + "%\n");
  80. }
  81. bin.close();
  82. out.close();
  83. } catch (MalformedURLException e) {
  84. // TODO Auto-generated catch block
  85. e.printStackTrace();
  86. } catch (IOException e) {
  87. // TODO Auto-generated catch block
  88. e.printStackTrace();
  89. } finally {
  90. return file;
  91. }
  92. }
  93. }

这俩种方法其实差不多。第一种融合了第二种写法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值