Java通过网络Url下载文件到本地目录

public void downloadFileFromUrl(String fileUrl, String fileName) throws Exception {
    URL url = new URL(fileUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setConnectTimeout(6000);
    urlConnection.setReadTimeout(6000);
    if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException("文件读取失败");
    }
    InputStream inputStream = urlConnection.getInputStream();
    byte[] buffer = new byte[1024];
    int len;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    while ((len = inputStream.read(buffer)) != -1) {
        byteArrayOutputStream.write(buffer, 0, len);
    }
    byteArrayOutputStream.close();
    File file = new File(System.getProperty("java.io.tmpdir") + fileName);
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    fileOutputStream.write(byteArrayOutputStream.toByteArray());
    fileOutputStream.close();
    inputStream.close();
    System.out.println("下载成功:" + System.getProperty("java.io.tmpdir") + fileName);
}

你可能感兴趣的:(java,开发语言)