网络文件下载

    private static void downLoadFile(String sourcePath, String targetPathDir, String targetFileName) {
        try {
            URL url = new URL(sourcePath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            int code = conn.getResponseCode();
            InputStream is = null;
            FileOutputStream fos = new FileOutputStream(new File(targetPathDir, targetFileName));
            byte[] buff = new byte[1024];
            int len = 0;
            if (code == 200) {
                is = conn.getInputStream();
                while ((len = is.read(buff)) != -1) {
                    fos.write(buff,0,len);
                }
            }
            fos.close();
            is.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

posted @ 2015-11-12 14:18  一路向北中  阅读(155)  评论(0)    收藏  举报