1. 程式人生 > 其它 >遠端下載檔案到本地

遠端下載檔案到本地

遠端下載檔案到本地

1、路徑地址的建立

String fileLocal = "D:" + File.separator + "test"
File tempFile = new File(fileLocal);
  if (!tempFile.exists()) {// 如果路徑不存在
    if (!tempFile.isDirectory()) {// 如果是路徑
        tempFile.mkdirs();// 建立路徑
    }
}

2、下載檔案到本地方法

    /**
     * 下載檔案到本地
     * @param fileUrl 遠端地址
     * @param fileLocal 本地路徑 D:/test
     * @throws Exception
     */
    public static void downloadFile(String fileUrl,String fileLocal){
        DataInputStream in =null;
        DataOutputStream out =null;
        HttpURLConnection urlCon =null;
        try{
            if(StringUtils.isNotBlank(fileUrl)){
                LOG.info("下載檔案到本地fileUrl="+fileUrl);
                URL url = new URL(fileUrl);
                urlCon = (HttpURLConnection) url.openConnection();
                urlCon.setConnectTimeout(6000);
                urlCon.setReadTimeout(6000);
                int code = urlCon.getResponseCode();
                if (code != HttpURLConnection.HTTP_OK) {
                    throw new Exception("檔案讀取失敗");
                }
                //讀檔案流
                in = new DataInputStream(urlCon.getInputStream());
                out = new DataOutputStream(new FileOutputStream(fileLocal));
                byte[] buffer = new byte[2048];
                int count = 0;
                while ((count = in.read(buffer)) > 0) {
                    out.write(buffer, 0, count);
                }
            }
        }catch (Exception e) {
            LOG.error("", e);
        }finally{
            try{if(out!=null)out.close();}catch (Exception e) {}
            try{if(in!=null)in.close();}catch (Exception e) {}
            try{if(urlCon!=null)urlCon.disconnect();}catch (Exception e) {}
        }
    }