java追加文件下载

  1. /** 
  2.      * 从网络Url中下载文件 
  3.      * @param urlStr 
  4.      * @param fileName 
  5.      * @param savePath 
  6.      * @throws IOException 
  7.      */  
  8.     public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{  
  9.         URL url = new URL(urlStr);    
  10.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
  11.                 //设置超时间为3秒  
  12.         conn.setConnectTimeout(3*1000);  
  13.         //防止屏蔽程序抓取而返回403错误  
  14.         conn.setRequestProperty("User-Agent""Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
  15.   
  16.         //得到输入流  
  17.         InputStream inputStream = conn.getInputStream();    
  18.         //获取自己数组  
  19.         byte[] getData = readInputStream(inputStream);      
  20.   
  21.         //文件保存位置  
  22.         File saveDir = new File(savePath);  
  23.         if(!saveDir.exists()){  
  24.             saveDir.mkdir();  
  25.         }  
  26.         File file = new File(saveDir+File.separator+fileName);      
  27.         FileOutputStream fos = new FileOutputStream(file);       
  28.         fos.write(getData);   
  29.         if(fos!=null){  
  30.             fos.close();    
  31.         }  
  32.         if(inputStream!=null){  
  33.             inputStream.close();  
  34.         }  
  35.   
  36.   
  37.         System.out.println("info:"+url+" download success");   
  38.   
  39.     }  
  40.   
  41.   
  42.   
  43.     /** 
  44.      * 从输入流中获取字节数组 
  45.      * @param inputStream 
  46.      * @return 
  47.      * @throws IOException 
  48.      */  
  49.     public static  byte[] readInputStream(InputStream inputStream) throws IOException {    
  50.         byte[] buffer = new byte[1024];    
  51.         int len = 0;    
  52.         ByteArrayOutputStream bos = new ByteArrayOutputStream();    
  53.         while((len = inputStream.read(buffer)) != -1) {    
  54.             bos.write(buffer, 0, len);    
  55.         }    
  56.         bos.close();    
  57.         return bos.toByteArray();    
  58.     }    
  59.   
  60.     public static void main(String[] args) {  
  61.         try{  
  62.             downLoadFromUrl("http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",  
  63.                     "百度.jpg","d:/resource/images/diaodiao/country/");  
  64.         }catch (Exception e) {  
  65.             // TODO: handle exception  
  66.         }  
  67. 通过url 下载文件

    1、问题简介

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

    2、实现思路

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

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

    3、代码实现

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

    java追加文件下载
    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"));
        }
    }
    java追加文件下载

     

    2)、文件下载类

    java追加文件下载
    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/[email protected]", "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();
            }
        }   
    }
    java追加文件下载

     

    3)、网页调用

    URLConnectionDownloader.downloadToSelectedFolder("android_banner_url","picture.properties","http://stocardapp.s3-external-3.amazonaws.com/ios/icons/[email protected]","2x.png",request);

     

    4)、测试结果

    网页的图片:

    java追加文件下载

    下载的图片

    java追加文件下载

      致谢:感谢您的阅读!


  68.     }  
  69. /**
         * 从网络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
            }
        }

  70. 参考文章:

    http://blog.****.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来获取资源。

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

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

    URLConnections 类方法

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

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

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

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

    [html] view plain copy
    1. /**   
    2.      * 从网络Url中下载文件   
    3.      * @param urlStr   
    4.      * @param fileName   
    5.      * @param savePath   
    6.      * @throws IOException   
    7.      */    
    8.     public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{    
    9.         URL url = new URL(urlStr);      
    10.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();      
    11.                 //设置超时间为3秒    
    12.         conn.setConnectTimeout(3*1000);    
    13.         //防止屏蔽程序抓取而返回403错误    
    14.         conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");    
    15.     
    16.         //得到输入流    
    17.         InputStream inputStream = conn.getInputStream();      
    18.         //获取自己数组    
    19.         byte[] getData = readInputStream(inputStream);        
    20.     
    21.         //文件保存位置    
    22.         File saveDir = new File(savePath);    
    23.         if(!saveDir.exists()){    
    24.             saveDir.mkdir();    
    25.         }    
    26.         File file = new File(saveDir+File.separator+fileName);        
    27.         FileOutputStream fos = new FileOutputStream(file);         
    28.         fos.write(getData);     
    29.         if(fos!=null){    
    30.             fos.close();      
    31.         }    
    32.         if(inputStream!=null){    
    33.             inputStream.close();    
    34.         }    
    35.     
    36.     
    37.         System.out.println("info:"+url+" download success");     
    38.     
    39.     }    
    40.     
    41.     
    42.     
    43.     /**   
    44.      * 从输入流中获取字节数组   
    45.      * @param inputStream   
    46.      * @return   
    47.      * @throws IOException   
    48.      */    
    49.     public static  byte[] readInputStream(InputStream inputStream) throws IOException {      
    50.         byte[] buffer = new byte[1024];      
    51.         int len = 0;      
    52.         ByteArrayOutputStream bos = new ByteArrayOutputStream();      
    53.         while((len = inputStream.read(buffer)) != -1) {      
    54.             bos.write(buffer, 0, len);      
    55.         }      
    56.         bos.close();      
    57.         return bos.toByteArray();      
    58.     }      
    59.     
    60.     public static void main(String[] args) {    
    61.         try{    
    62.             downLoadFromUrl("http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",    
    63.                     "baidu.jpg","D:/");    
    64.         }catch (Exception e) {    
    65.             // TODO: handle exception    
    66.         }    
    67.     }    

    记录一下这个:

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