分享

java从http url下载文件的方法

 超越郑越超 2011-03-11
  1. import java.io.File;   
  2. import java.net.URL;   
  3.   
  4. import org.apache.commons.io.FileUtils;   
  5.   
  6. public class DownloadURLFile {   
  7.   
  8.     /**  
  9.      * @param args  
  10.      */  
  11.     public static void main(String[] args) {   
  12.   
  13.         String res = downloadFromUrl("http://images.17173.com/2010/www/roll/201003/0301sohu01.jpg","d:/");   
  14.         System.out.println(res);   
  15.     }   
  16.   
  17.   
  18.     public static String downloadFromUrl(String url,String dir) {   
  19.   
  20.         try {   
  21.             URL httpurl = new URL(url);   
  22.             String fileName = getFileNameFromUrl(url);   
  23.             System.out.println(fileName);   
  24.             File f = new File(dir + fileName);   
  25.             FileUtils.copyURLToFile(httpurl, f);   
  26.         } catch (Exception e) {   
  27.             e.printStackTrace();   
  28.             return "Fault!";   
  29.         }    
  30.         return "Successful!";   
  31.     }   
  32.        
  33.     public static String getFileNameFromUrl(String url){   
  34.         String name = new Long(System.currentTimeMillis()).toString() + ".X";   
  35.         int index = url.lastIndexOf("/");   
  36.         if(index > 0){   
  37.             name = url.substring(index + 1);   
  38.             if(name.trim().length()>0){   
  39.                 return name;   
  40.             }   
  41.         }   
  42.         return name;   
  43.     }   
  44. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多