Java: 无法读取我在会话期间复制的文件,程序重启后工作正常

Java: Can't read file I copied during session, works fine after program restart

我正在复制这样的文件:

            File copy = new File(file.getName());
            // path relative to current working directory
            Path relativePath = Paths.get("src/main/resources/images/",  copy.getPath());
            java.nio.file.Files.copy(
                    file.toPath(), // input path
                    relativePath, // target path
                    java.nio.file.StandardCopyOption.REPLACE_EXISTING);

            logger.info("Copy file to path {}", relativePath);
            // save path for NPC
            currentImagePath = "/images/"+copy.getPath();

然后保存到数据库的路径。当我尝试像这样打开复制的文件时:

            Image image = new Image(bild);

(bild 是之前的 currentImagePath),我收到一个异常,指出它是无效的 URL 或找不到资源。但是,如果我结束程序并重新启动它,则打开文件没有问题。有针对这个的解决方法吗?

可能文件还没有复制完成。复制文件可能需要 OS 一段时间。 copy 方法可能会在复制完成之前 return。

如果没有看到更多代码,我会说你的问题是这一行 Image image = new Image(bild);

此外 "/images/"+copy.getPath()relativePath 不同,您是否正确使用了它们?试试这个检查是否有问题:

System.out.println("/images/"+copy.getPath());
System.out.println(relativePath);
System.out.println(copy.getAbsolutePath());

您的问题是否由错误的路径引起?

现在尝试像这样加载图像(注意 ImageIO 的使用方式):

System.out.println("Does file exist: "+ copy.exists());
System.out.println("Is file locked: "+ copy.canWrite());
while (copy.canWrite() != true){
    //stall your application until the file is accessible.
}
//now load the file
Image image = ImageIO.read(copy);

此答案提供了有关检查锁定文件的极好信息: