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
相关产品推荐
相关产品推荐

