java網上下載文件

java下載文件

  • 1.使用httpClient下載文件:
/*
*url:資源的地址:http://***.**.***.**.a.mp4
*
*/
public void downLoadFile(String url) throws IOException {

        // 生成一個httpclient對象
        CloseableHttpClient httpclient = Usual.httpClient;
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();

        File file = new File("D://zcq/b.mp4");//這裏爲存儲路徑/xx/xx..

        FileOutputStream fout = new FileOutputStream(file);
        int a = -1;
        byte[] tmp = new byte[1024];
        while ((a = in.read(tmp)) != -1) {
            fout.write(tmp, 0, a);
            //注意這裏如果用OutputStream.write(buff)的話,圖片會失真,大家可以試試
        }
        fout.flush();
        fout.close();
        in.close();
        httpclient.close();

    }
public static boolean httpDownload(String httpUrl, String saveFile) {
        // 1.下載網絡文件
        int byteRead;
        URL url;
        try {
            url = new URL(httpUrl);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            return false;
        }

        try {
            //2.獲取鏈接
            URLConnection conn = url.openConnection();
            //3.輸入流
            InputStream inStream = conn.getInputStream();
            //3.寫入文件
            FileOutputStream fs = new FileOutputStream(saveFile);

            byte[] buffer = new byte[1024];
            while ((byteRead = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteRead);
            }
            inStream.close();
            fs.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    public static void main(String[] args) {
        httpDownload("http://***.***.***/hanghaibaolei.mp4","D://shg.mp4");
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章