1. 程式人生 > >java實現從網上下載檔案到本地

java實現從網上下載檔案到本地

基本實現步驟:

1.建立http連線,獲取物件 connection

2.輸入流讀檔案

3.新建儲存路徑

4.輸出流寫入資料,並關閉流

public class test {

public static void main(String[] args) {
getInternetRes("D:\\demoefile","http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=3d2175db3cd3d539d530078052ee8325/b7003af33a87e950c1e1a6491a385343fbf2b425.jpg","112.jpg");

}

public static void getInternetRes(String newUrl, String oldUrl, String fileName) {
        URL url = null;
        HttpURLConnection con = null;
        InputStream in = null;
        FileOutputStream out = null;
        try {
            url = new URL(oldUrl);
           //建立http連線,得到連線物件
           con = (HttpURLConnection) url.openConnection();
           //輸入流讀取檔案
           in = con.getInputStream();
           //轉化為byte陣列
           byte[] data = getByteData(in);
           //建立儲存的目錄、儲存的檔名 
           File file = new File(newUrl+today);
           if (!file.exists()) {
               file.mkdirs();
           }
           //修改檔名   用id重新命名
           File res = new File(file + File.separator + fileName);
           //寫入輸出流
           out = new FileOutputStream(res);
           out.write(data);
          logger.info("下載 successfully!");
       } catch (MalformedURLException e) {
        logger.error("下載出錯!"+e.toString());
       } catch (IOException e) {
        logger.error("下載出錯!"+e.toString());
       } finally {
        //關閉流
           try {
               if (null != out)
                   out.close();
               if (null != in)
                   in.close();
           } catch (IOException e) {
            logger.error("下載出錯!"+e.toString());
           }
       }
}
return null;
}

/**

* @Title: getByteData
* @Description: 從輸入流中獲取位元組陣列
* @author zml
* @date Sep 12, 2017 7:38:57 PM
*/
private static byte[] getByteData(InputStream in) throws IOException {
       byte[] b = new byte[1024];
       ByteArrayOutputStream bos = new ByteArrayOutputStream();
       int len = 0;
       while ((len = in.read(b)) != -1) {
           bos.write(b, 0, len);
       }
       if(null!=bos){
           bos.close();
       }
       return bos.toByteArray();
   }