使用java代码通过URL将图片下载保存到本地

发布时间 2023-08-30 16:00:36作者: 且行且思
String imageUrl = "http://example.com/image.jpg"; // 替换成你需要下载的图片URL
String savePath = "/path/to/your/save/directory/image.jpg"; // 替换成你需要保存图片的本地目录
try {
    // 打开连接
    URL url = new URL(imageUrl);
    URLConnection connection = url.openConnection();
    // 设置请求超时为5秒
    connection.setConnectTimeout(5 * 1000);
    // 读取数据流并保存到本地
    InputStream input = connection.getInputStream();
    byte[] data = new byte[2048];
    int len;
    FileOutputStream output = new FileOutputStream(savePath);
    while ((len = input.read(data)) != -1) {
        output.write(data, 0, len);
    }
    output.close();
    input.close();
    System.out.println("图片保存成功:" + savePath);
} catch (IOException e) {
    e.printStackTrace();
    System.out.println("图片保存失败:" + e.getMessage());
}
  • 在以上示例中,我们定义了一个需要下载的图片URL和需要保存图片的本地路径。
  • 我们使用URL类打开连接,设置连接的请求超时时间,然后读取输入流中的图片数据并将其保存到本地目录中。
  • 最后,关闭输入流和输出流对象。