1. 程式人生 > >工具類—Java下載遠端檔案到本地

工具類—Java下載遠端檔案到本地

package com.alipay.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Name: RemoteFile.java
 * @Description: Java下載遠端檔案到本地。
 * @Author: PeiFeng
 * @Create Date: 2017-8-12
 */
public class RemoteFile {

    public static void main(String[] args) throws Exception {

        downRemoteFile(
                "https://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=http%3A%2F%2Fh.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F060828381f30e9240ff2cd434c086e061d95f76a.jpg&thumburl=https%3A%2F%2Fss2.bdstatic.com%2F70cFvnSh_Q1YnxGkpoWK1HF6hhy%2Fit%2Fu%3D2504031429%2C1727248259%26fm%3D26%26gp%3D0.jpg",
                "sssss.jpg", "D:/sss");

    }

    /**
     * @Name: downRemoteFile。
     * @Description: 下載遠端檔案。
     * @Parameters: remoteFileUrl,要下載的遠端檔案地址。
     * @Parameters: saveFileName,下載後儲存的檔名。
     * @Parameters: saveDir,下載後儲存的檔案路徑。
     * @Return: String,檔案儲存的地址。
     * @Author: PeiFeng
     * @Version: V1.00
     * @Create Date: 2017-8-12
     */
    public static String downRemoteFile(String remoteFileUrl, String saveFileName, String saveDir) {

        HttpURLConnection conn = null;
        OutputStream oputstream = null;
        InputStream iputstream = null;

        try {
            // 建立儲存檔案的目錄
            File savePath = new File(saveDir);
            if (!savePath.exists()) {
                savePath.mkdir();
            }
            // 建立儲存的檔案
            File file = new File(savePath + "/" + saveFileName);
            if (file != null && !file.exists()) {
                file.createNewFile();
            }

            URL url = new URL(remoteFileUrl);
            // 將url以open方法返回的urlConnection連線強轉為HttpURLConnection連線(標識一個url所引用的遠端物件連線)
            // 此時cnnection只是為一個連線物件,待連線中
            conn = (HttpURLConnection) url.openConnection();
            // 設定是否要從 URL連線讀取資料,預設為true
            conn.setDoInput(true);
            // 建立連線
            // (請求未開始,直到connection.getInputStream()方法呼叫時才發起,以上各個引數設定需在此方法之前進行)
            conn.connect();
            // 連線發起請求,處理伺服器響應 (從連接獲取到輸入流)
            iputstream = conn.getInputStream();
            // 建立檔案輸出流,用於儲存下載的遠端檔案
            oputstream = new FileOutputStream(file);
            //  用來儲存響應資料
            byte[] buffer = new byte[4 * 1024];
            int byteRead = -1;
            //  迴圈讀取流
            while ((byteRead = (iputstream.read(buffer))) != -1) {
                oputstream.write(buffer, 0, byteRead);
            }
            //  輸出完成後重新整理並關閉流
            oputstream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //  重要且易忽略步驟 (關閉流,切記!)
                if (iputstream != null) {
                    iputstream.close();
                }
                if (oputstream != null) {
                    oputstream.close();
                }
                // 銷燬連線
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 返回儲存後的檔案路徑
        return saveDir + "/" + saveFileName;
    }
}
轉載 http://blog.csdn.net/u012758088/article/details/77119530?locationNum=4&fps=1

相關推薦

工具Java下載遠端檔案本地

package com.alipay.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; i

Java通用的Excel檔案生成工具,支援生成檔案和瀏覽器直接下載

<span style="font-size:14px;">java通用的Excel檔案建立方法,支援同文件多tab頁建立。只需要呼叫靜態方法,傳遞List<String>表頭和List<Map>資料集合等,即可生成Excel檔案。 p

java常用工具(三)—— 檔案讀取的操作

定義常用的檔案型別 public class FileType { /** * 檔案頭型別 */ public static final String XML_FILE = "text/xml;charset=UTF-8"; public static

Java FTPClient 遠端檔案上傳下載追加

注意事項: 匯入jar包:commons-net-3.6.jar(百度雲分享) 用於登陸FTP伺服器的賬戶對檔案操作目錄必須有讀寫許可權 import java.io.File; import java.io.FileInputStream; import java.

快取工具 使用IO流寫入本地檔案

/** * Copyright (c) 2012-2013, Michael Yang 楊福海 (www.yangfuhai.com). * * Licensed under the Apache License, Version 2.0 (the "License")

JAVA開發經驗(二):常用工具2.1-IO-檔案操作(FileUtil)

摘要說明: FileUtil主要是整合Apache Commons IO庫中的FileUtils類;主要包括對檔案的屬性查詢,複製,移動,檔案讀取,刪除等 Apache Commons IO庫包含實用程式類,流實現,檔案過濾器,檔案比較器,位元組序轉換類等等 Maven

JAVA下載遠端Linux伺服器的檔案

<h1><span style="background-color: rgb(255, 255, 255);">RemoteAccessData.java</span></h1>package com.yzj.demo; im

xstream--xml工具--java物件轉換JSONObject、xml與java物件互轉

工作環境: myeclipse2013、jdk1.8、fastjson1.1.41、xstream1.4.3 import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Writer;

前端下載遠端檔案

前端網頁下載遠端檔案可以分為以下兩種形式: 開啟新視窗下載 在當前視窗直接下載 開啟新視窗下載的方法: window.open方法(開啟一個彈窗): window.open('http://xxx/download?param=1&param2', '_blank'

通用工具,獲取配置檔案資訊

創作不易,請勿抄襲,轉載請註明出處。如有疑問,請加微信 wx15151889890,謝謝。 [本文連結:]https://blog.csdn.net/wx740851326/article/details/83744404 之前已經寫過了這個文章,現在把整個類粘出來 文章也用markdo

Http請求工具(Java原生Form+Json)

package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputSt

使用Python下載工具you-get下載媒體檔案

You-Get是一個基於 Python 3 的下載工具。使用 You-Get 可以很輕鬆的下載到網路上的視訊、圖片及音樂。 使用you-get下載媒體檔案 1.安裝Python(步驟詳情見另一篇文章) 2.安裝you-get         1.開啟cmd,輸

寫jdbc的工具 java

為什麼要有工具類 jdbc 連線資料庫中很常用,但程式碼量又多,所以編寫一個工具類是很重要的。 之前我們已經寫了jdbc連線的程式碼 這裡我們就寫 一個工具類並實現 程式碼 public class JDBCUtil { static String driverClass

工具——Java時間戳與日期格式字串的互轉

import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { /** * 時間戳轉換成日期格式字串 * @param seconds 精確到

微信支付 XML解析工具 JAVA

package utils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEn

方差計算工具--Java

方差的計算,如果不太計較精度的話,可以使用 Apache 的 commons-math3(http://commons.apache.org/proper/commons-math/)提供的 Variance 類。不過畢竟 Variance 是使用 double 進行計算,會

springboot 專案框架搭建(三):工具中讀取配置檔案

一.原因     編寫一個服務類的工具類,想做成一個靈活的配置,各種唯一code想從配置檔案中讀取,便有了這個坑。  二.使用@value獲取值為null,     這是因為這個工具類沒有交給spring boot 來管理,導致每次都是new 一個新的,所以每次取出來的

Java下載圖片到本地

1、首先頁面請求不可以用ajax請求,否則會將資訊輸出到控制檯 var url = "${path}/pc/qrcode/downLoad.do?filename="+ 檔案路徑 +"&imgName=" +儲存的檔名稱; window.location.href

RSA加密工具(Java)

乾貨 package com.hht.exchange.utils; import javax.crypto.Cipher; import java.security.*; import java.security.spec.PKCS8EncodedKeySp

寫爬蟲所用到的工具---(3)[檔案]

package Tool; import java.io.*; import java.util.ArrayList; import java.util.List; /** * this is a class that can operation file