java下载文件到本地

public static boolean downloadFile(String fileUrl, String fileLocal) throws Exception {
    boolean flag = false;
    URL url = new URL(fileUrl);
    HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
    urlCon.setConnectTimeout(6000);
    urlCon.setReadTimeout(6000);
    int code = urlCon.getResponseCode();
    if (code != HttpURLConnection.HTTP_OK) {
        throw new Exception("文件读取失败");
    }
    //读文件流
    DataInputStream in = new DataInputStream(urlCon.getInputStream());
    DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
    byte[] buffer = new byte[2048];
    int count = 0;
    while ((count = in.read(buffer)) > 0) {
        out.write(buffer, 0, count);
    }
    try {
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    flag = true;
    return flag;
}

版权声明:本文为qq_34625907原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。