Download file via HTTP with unknown length with Java

后端 未结 1 523
野趣味
野趣味 2021-02-09 19:58

I want to download a HTTP query with java, but the file I download has an undetermined length when downloading.

I thought this would be quite standard, so I searched and

相关标签:
1条回答
  • 2021-02-09 20:35

    This should work, i tested it and it works for me:

    void downloadFromUrl(URL url, String localFilename) throws IOException {
        InputStream is = null;
        FileOutputStream fos = null;
    
        try {
            URLConnection urlConn = url.openConnection();//connect
    
            is = urlConn.getInputStream();               //get connection inputstream
            fos = new FileOutputStream(localFilename);   //open outputstream to local file
    
            byte[] buffer = new byte[4096];              //declare 4KB buffer
            int len;
    
            //while we have availble data, continue downloading and storing to local file
            while ((len = is.read(buffer)) > 0) {  
                fos.write(buffer, 0, len);
            }
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }
    }
    

    If you want this to run in background, simply call it in a Thread:

    Thread download = new Thread(){
        public void run(){
            URL url= new URL("http://overpass-api.de/api/interpreter?data=area%5Bname%3D%22Hoogstade%22%5D%3B%0A%28%0A++node%28area%29%3B%0A++%3C%3B%0A%29+%3B%0Aout+meta+qt%3B");
            String localFilename="mylocalfile"; //needs to be replaced with local file path
            downloadFromUrl(url, localFilename);
        }
    };
    download.start();//start the thread
    
    0 讨论(0)
提交回复
热议问题