java實現網上下載文件到本地

思路:
要弄清網上下載文件的一些關鍵邏輯。我們要從網上獲取信息,第一步必須要有網絡連接(connection),接着是你要獲取信息的路徑(ResourceUrl),然後你要對獲取到的信息的處理(process),而在這裏我們對信息的處理是“下載文件到本地”,下載要確定好保存位置(SavePath)。
由此,我們可以得到的簡單的思維順序是:建立連接——>得到源url——>確定保存位置。於是有下面的基本步驟。

基本步驟:
1.建立http連接,獲取連接對象
2.輸入流讀取文件
3.建立存儲的目錄、保存的文件名
4.輸出流寫數據
5.關閉流

主要方法:

/**
 * 網上獲取文件
 * 
 * @param savepath 保存路徑
 * @param resurl  資源路徑
 * @param fileName  自定義資源名
 */
public void getInternetRes(String savepath, String resurl, String fileName) {
        URL url = null;
        HttpURLConnection con = null;
        InputStream in = null;
        FileOutputStream out = null;
        try {
            url = new URL(resurl);
            //建立http連接,得到連接對象
            con = (HttpURLConnection) url.openConnection();
            //con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            in = con.getInputStream();
            byte[] data = getByteData(in);//轉化爲byte數組

            File file = new File(savepath);
            if (!file.exists()) {
                file.mkdirs();
            }

            File res = new File(file + File.separator + fileName);
            out = new FileOutputStream(res);
            out.write(data);
            System.out.println("downloaded successfully!");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out)
                    out.close();
                if (null != in)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
/**
     * 從輸入流中獲取字節數組
     * 
     * @param in
     * @return
     * @throws IOException
     */
    private byte[] getByteData(InputStream in) throws IOException {
        byte[] b = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len = 0;
        while ((len = in.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        if(null!=bos){
            bos.close();
        }
        return bos.toByteArray();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章