You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

URL转本地文件仅调试模式可用,运行时抛FileNotFoundException求解

图片URL转本地文件保存的异常问题及解决

我编写了以下代码,用于将URL中的图片转换为文件并保存到指定文件夹:

public void saveFileToStorage(String url, Long timestamp, Integer deviceId) {
    String folder = "D:\\Work\\S3\\" + deviceId;
    File directory = new File(folder);
    File file = new File(folder, timestamp + ".jpg");
    if (!directory.exists()) {
        directory.mkdir();
    }
    try {
        URL link = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) link.openConnection();
        BufferedImage image = ImageIO.read(connection.getInputStream());
        ImageIO.write(image, "jpg", file);
        connection.disconnect();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

这段代码仅在调试模式下能正常运行,直接启动程序时,多数情况会抛出java.lang.RuntimeException: java.io.FileNotFoundException异常。我尝试跳过HttpURLConnection,直接使用ImageIO.read(URL)方法读取图像,但始终抛出“Can't get input stream from URL!”异常——仅调试模式下可正常执行。

问题已解决!
原因是目标URL对应的文件存在上传延迟,程序运行速度过快,在文件尚未可下载时就发起了请求,因此触发FileNotFoundException。添加Thread.sleep(1000)后,程序可正常运行。

内容的提问来源于stack exchange,提问作者VegetaSan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:50:21