java追加文件下载

xiaoxiao2021-02-28  76

/**       * 从网络Url中下载文件       * @param urlStr       * @param fileName       * @param savePath       * @throws IOException       */       public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{           URL url = new URL(urlStr);             HttpURLConnection conn = (HttpURLConnection)url.openConnection();                     //设置超时间为3秒           conn.setConnectTimeout(3*1000);           //防止屏蔽程序抓取而返回403错误           conn.setRequestProperty("User-Agent""Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");              //得到输入流           InputStream inputStream = conn.getInputStream();             //获取自己数组           byte[] getData = readInputStream(inputStream);                  //文件保存位置           File saveDir = new File(savePath);           if(!saveDir.exists()){               saveDir.mkdir();           }           File file = new File(saveDir+File.separator+fileName);               FileOutputStream fos = new FileOutputStream(file);                fos.write(getData);            if(fos!=null){               fos.close();             }           if(inputStream!=null){               inputStream.close();           }                 System.out.println("info:"+url+" download success");           }                /**       * 从输入流中获取字节数组       * @param inputStream       * @return       * @throws IOException       */       public static  byte[] readInputStream(InputStream inputStream) throws IOException {             byte[] buffer = new byte[1024];             int len = 0;             ByteArrayOutputStream bos = new ByteArrayOutputStream();             while((len = inputStream.read(buffer)) != -1) {                 bos.write(buffer, 0, len);             }             bos.close();             return bos.toByteArray();         }            public static void main(String[] args) {           try{               downLoadFromUrl("http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",                       "百度.jpg","d:/resource/images/diaodiao/country/");           }catch (Exception e) {               // TODO: handle exception           }  

通过url 下载文件

1、问题简介

  通过文件的url,将文件下载到本地。文件存储的位置为:tomcat服务器的文件夹(通过读取properties文件:可看:http://www.cnblogs.com/0201zcr/p/4700418.html)

2、实现思路

  读取properties文件,将获得文件将要存储的位置

  通过java的Url类,将网上的文件下载到本地

3、代码实现

1)、读取properties文件(这里建立的是一个web project)

package com.zcr.until; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class GetFilePlace { /** * 读取文件,获取保存的根目录 * @return 保存的根目录 */ public String getFilePath(String fileProperties) { String dir = System.getProperty("user.dir"); //获得tomcat所在的工作路径 //获取到存储了文件存储位置的filedir.properties 文件路径 // String realDir = dir + File.separator + "src" + File.separator +"META-INF" + File.separator + "config" + File.separator + "picture.properties"; String realDir = dir.substring(0, dir.length()-4) + File.separator +"webapps" + File.separator + "appDataGenerate" +File.separator + "WEB-INF" + File.separator + "classes" + File.separator + "META-INF" + File.separator + "config" + File.separator + fileProperties; /* String realDir = dir.substring(0, dir.length()-4) + File.separator +"webapps" + File.separator + "appDataGenerate" + File.separator + "classes" + File.separator + "META-INF" + File.separator + "config" + File.separator + fileProperties; */ System.out.println("realDir = " + realDir); return realDir; } /** * 获取filePath路径【properities文件】中key对应的值, * @param filePath properities文件路径【包含properities文件】 * @param key 要查找的key值 * @return key对应的value */ public String GetValueByKey(String filePath, String key) { Properties pps = new Properties(); try { InputStream in = new BufferedInputStream (new FileInputStream(filePath)); pps.load(in); String value = pps.getProperty(key); in.close(); return value; }catch (IOException e) { e.printStackTrace(); return null; } } /** * 查询properities文件中可以对应的存储地点 * @param key 查询主键 * @return key对应的存储地址 */ public String getFileDirFromProperties(String key,String fileProperties) { return GetValueByKey(getFilePath(fileProperties),key); } public static void main(String[] args) { System.out.println(new GetFilePlace().getFileDirFromProperties("brandLogo","picture.properties")); } }

 

2)、文件下载类

package com.zcr.until; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import javax.servlet.http.HttpServletRequest; public class URLConnectionDownloader { //单纯测试下载 public static void main(String[] args) { download("http://stocardapp.s3-external-3.amazonaws.com/ios/icons/1001tur@2x.png", "E:\\xiazai.jpg"); } /** * 将urlString的文件下载到 * @param filePathName properties文件中的文件存储名 * @param fileProperties 查找的properties文件 * @param urlString 待下载的文件url * @param fileName 生成的文件名称 */ public static void downloadToSelectedFolder(String filePathName,String fileProperties,String urlString,String fileName,HttpServletRequest request) { //获得picture.properties 文件中,key为android_banner_url的值 String pathSavePath = new GetFilePlace().getFileDirFromProperties("android_banner_url","picture.properties"); //获得服务器(tomcat)pathSavePath的相对位置 String path = request.getSession().getServletContext().getRealPath(pathSavePath); //获得文件存储的绝对路径 String generateFileName = path + File.separator + fileName; download(urlString,generateFileName); } /** * 下载文件到本地 * * @param urlString * 被下载的文件地址 * @param filename * 本地文件名 */ public static void download(String urlString, String filename) { // 构造URL URL url; try { url = new URL(urlString); // 打开连接 URLConnection con = url.openConnection(); // 输入流 InputStream is = con.getInputStream(); // 1K的数据缓冲 byte[] bs = new byte[1024]; // 读取到的数据长度 int len; // 输出的文件流s OutputStream os = new FileOutputStream(filename); // 开始读取 while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } // 完毕,关闭所有链接 os.close(); is.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

 

3)、网页调用

URLConnectionDownloader.downloadToSelectedFolder("android_banner_url","picture.properties","http://stocardapp.s3-external-3.amazonaws.com/ios/icons/1001tur@2x.png","2x.png",request);

 

4)、测试结果

网页的图片:

下载的图片

  致谢:感谢您的阅读!

    }   /** * 从网络Url中下载文件 * @param urlStr * @param fileName * @param savePath * @throws IOException */ public static void downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{ URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(3*1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 InputStream inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); if(!saveDir.exists()){ saveDir.mkdir(); } File file = new File(saveDir+File.separator+fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if(fos!=null){ fos.close(); } if(inputStream!=null){ inputStream.close(); } System.out.println("info:"+url+" download success"); } /** * 从输入流中获取字节数组 * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } public static void main(String[] args) { try{ downLoadFromUrl("http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png", "百度.jpg","d:/resource/images/diaodiao/country/"); }catch (Exception e) { // TODO: handle exception } }

参考文章:

http://blog.csdn.NET/xb12369/article/details/40543649/

http://www.runoob.com/Java/java-url-processing.html

有时候我们需要从网络或者资源服务器等外部非本地环境下载文件,这就需要我们通过URL来访问地址。

URL(Uniform Resource Locator)中文名为统一资源定位符,有时也被俗称为网页地址。表示为互联网上的资源,如网页或者FTP地址。

java.net.URL提供了丰富的URL构建方式,并可以通过java.Net.URL来获取资源。

序号方法描述1public URL(String protocol, String host, int port, String file) throws MalformedURLException. 通过给定的参数(协议、主机名、端口号、文件名)创建URL。2public URL(String protocol, String host, String file) throws MalformedURLException 使用指定的协议、主机名、文件名创建URL,端口使用协议的默认端口。3public URL(String url) throws MalformedURLException 通过给定的URL字符串创建URL4public URL(URL context, String url) throws MalformedURLException 使用基地址和相对URL创建URL类中包含了很多方法用于访问URL的各个部分,具体方法及描述如下:

序号方法描述1public String getPath() 返回URL路径部分。2public String getQuery() 返回URL查询部分。3public String getAuthority() 获取此 URL 的授权部分。4public int getPort() 返回URL端口部分5public int getDefaultPort() 返回协议的默认端口号。6public String getProtocol() 返回URL的协议7public String getHost() 返回URL的主机8public String getFile() 返回URL文件名部分9public String getRef() 获取此 URL 的锚点(也称为"引用")。10public URLConnection openConnection() throws IOException 打开一个URL连接,并运行客户端访问资源。

URLConnections 类方法

openConnection() 返回一个 java.net.URLConnection。 例如: 如果你连接HTTP协议的URL, openConnection() 方法返回 HttpURLConnection 对象。 如果你连接的URL为一个 JAR 文件, openConnection() 方法将返回 JarURLConnection 对象。 等等... URLConnection 方法列表如下:

序号方法描述1Object getContent()  检索URL链接内容2Object getContent(Class[] classes)  检索URL链接内容3String getContentEncoding()  返回头部 content-encoding 字段值。4int getContentLength()  返回头部 content-length字段值5String getContentType()  返回头部 content-type 字段值6int getLastModified()  返回头部 last-modified 字段值。7long getExpiration()  返回头部 expires 字段值。8long getIfModifiedSince()  返回对象的 ifModifiedSince 字段值。9public void setDoInput(boolean input) URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 true。10public void setDoOutput(boolean output) URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。11public InputStream getInputStream() throws IOException 返回URL的输入流,用于读取资源12public OutputStream getOutputStream() throws IOException 返回URL的输出流, 用于写入资源。13public URL getURL() 返回 URLConnection 对象连接的URL

下面是URL的工具方法,我们在downLoadFromUrl添加url地址,文件名称(自定义)和文件下载路径就可以在获取网页或者FTP上的文件。

建议:文件名,文件路径不要使用中文

[html]   view plain  copy /**        * 从网络Url中下载文件        * @param urlStr        * @param fileName        * @param savePath        * @throws IOException        */        public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{            URL url = new URL(urlStr);              HttpURLConnection conn = (HttpURLConnection)url.openConnection();                      //设置超时间为3秒            conn.setConnectTimeout(3*1000);            //防止屏蔽程序抓取而返回403错误            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");                //得到输入流            InputStream inputStream = conn.getInputStream();              //获取自己数组            byte[] getData = readInputStream(inputStream);                    //文件保存位置            File saveDir = new File(savePath);            if(!saveDir.exists()){                saveDir.mkdir();            }            File file = new File(saveDir+File.separator+fileName);                FileOutputStream fos = new FileOutputStream(file);                 fos.write(getData);             if(fos!=null){                fos.close();              }            if(inputStream!=null){                inputStream.close();            }                    System.out.println("info:"+url+" download success");             }                    /**        * 从输入流中获取字节数组        * @param inputStream        * @return        * @throws IOException        */        public static  byte[] readInputStream(InputStream inputStream) throws IOException {              byte[] buffer = new byte[1024];              int len = 0;              ByteArrayOutputStream bos = new ByteArrayOutputStream();              while((len = inputStream.read(buffer)) != -1) {                  bos.write(buffer, 0, len);              }              bos.close();              return bos.toByteArray();          }              public static void main(String[] args) {            try{                downLoadFromUrl("http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",                        "baidu.jpg","D:/");            }catch (Exception e) {                // TODO: handle exception            }        }    

记录一下这个:

[java]   view plain  copy File file = new File(path);// path是根据日志路径和文件名拼接出来的  String filename = file.getName();// 获取日志文件名称  InputStream fis = new BufferedInputStream(new FileInputStream(path));  byte[] buffer = new byte[fis.available()];  fis.read(buffer);  fis.close();  response.reset();  // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名  response.addHeader("Content-Disposition""attachment;filename=" + new String(filename.replaceAll(" """).getBytes("utf-8"),"iso8859-1"));  response.addHeader("Content-Length""" + file.length());  OutputStream os = new BufferedOutputStream(response.getOutputStream());  response.setContentType("application/octet-stream");  os.write(buffer);// 输出文件  os.flush();  
转载请注明原文地址: https://www.6miu.com/read-64987.html

最新回复(0)