簡體   English   中英

從URL下載文件

[英]Downloading File from URL

我用Java編寫了一個線程程序,用於從URL(https)下載文件。 有時,下載文件的大小會從其原始大小減小。

如何下載文件而不丟失數據?

public class Download extends Observable implements Runnable {
    private static final int MAX_BUFFER_SIZE = 1024;        
    public static final int DOWNLOADING = 0;    
    public static final int PAUSED = 1; 
    public static final int COMPLETE = 2;   
    public static final int CANCELLED = 3;  
    public static final int ERROR = 4;  
    private URL url; 
    private int size; 
    private int downloaded; 
    private int status; 

    public Download(URL url){
        this.url = url;
        size=-1;
        downloaded=0;
        status=DOWNLOADING;
        download();
    }

    public String getURL(){
        return url.toString();
    }   

    public void error(){
        status = ERROR;
        stateChanged();
    }

    private void download(){
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {     
        RandomAccessFile randomAccessFile = null;
        InputStream inputStream = null;
        try{
            HttpsURLConnection connection = getSSLCertficate(getURL());
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Range","bytes=" + downloaded + "-");
            connection.connect();
            if(connection.getResponseCode()/100 != 2){
                error();
            }
            int contentLength = connection.getContentLength();
            if(contentLength <1){
                error();
            }
            if(size == -1){
                size = contentLength;
                stateChanged();
            }
            randomAccessFile = new RandomAccessFile("/home/user/Desktop/dotproject-2.1.5.tar.gz","rw");         
            randomAccessFile.seek(downloaded);
            inputStream = connection.getInputStream();
            while(status == DOWNLOADING){
                byte buffer[];
                int finalSize=size - downloaded;
                if ( finalSize > MAX_BUFFER_SIZE) {
                    buffer = new byte[MAX_BUFFER_SIZE];
                } else {
                    buffer = new byte[size - downloaded];
                }
                int read = inputStream.read(buffer);
                if(read == -1)
                    break;              

                randomAccessFile.write(buffer, 0, read);                
                downloaded += read;             
                stateChanged();
            }           

        }catch (Exception e) {

        }
    }

    private void stateChanged(){
        setChanged();
        notifyObservers();
    }

    private HttpsURLConnection getSSLCertficate(String urlPath) throws NoSuchAlgorithmException, KeyManagementException, IOException{
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0],new TrustManager[]{new DefaultTrustManager()},new SecureRandom());
        SSLContext.setDefault(ctx);

        URL url = new URL(urlPath);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {               
                return true;
            }
        });

        return conn;
    }

    public static void main(String[] args) throws MalformedURLException {
        Download d = new Download(new URL("https://192.16.1.130/Source.tar.gz"));
        d.run();
    }

}

請在finally部分中關閉輸入流(它會自動刷新所有數據):

try {
    ....
} catch(...) {
    ...
} finally {
    // This will guaranty you get all data:
    inputStream.close();
}

您太復雜了。 這是復制字節流(任何字節流)的方法。

int count;
byte[] buffer = new byte[8192]; // you can tune this value
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}

您不需要大小為預期輸入長度的緩沖區; 您甚至不需要知道HttpURLConnection的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM