Java: 在不退出应用程序的情况下将图像保存到文件目录

Java: Save an image to a file directory without exiting application

我是 Whosebug 和 Java 的新手,所以如果这不是在正确的地方并且我对 Java 概念的理解不正确,我深表歉意。我在网上看了一圈,但没有找到解决我的问题的办法,我也不明白为什么会这样。

我正在制作一个应用程序,它可以截取我的屏幕截图并将其保存到项目的工作源目录中。保存图像后,另一个 window 打开并显示该图像。

我的问题是保存图像。我可以保存它,但是在我关闭整个程序之前,屏幕截图不会出现在项目目录中,因此导致错误,因为尽管图像不存在于文件目录中,但第一次无法读取图像它被保存。关闭它后,图像会显示在目录中,程序会正常运行 运行 第二次后没有错误。

我不明白为什么会这样。为什么直到程序终止后图像才出现在文件目录中,我将如何解决这个问题?我在 Inteliji Idea.[=12= 中使用 JavaFxFXML ]

如有任何帮助,我们将不胜感激。

// This method / function runs on a simple button press.
public void screenshot() throws Exception{


    // Hides the window
    boarderPane.getScene().getWindow().hide();

    String format = "jpg";
    String fileName = "FullScreenshot." + format;

            try {

                // This gives the window enough time to hide so it doesn't get caught in the screenshot
                Thread.sleep(500);


                Robot robot = new Robot();


                Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

                BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
                ImageIO.write(screenFullImage, format, new File("src\image\" + fileName));

                System.out.println("A full screenshot saved!");

            } catch (AWTException ex) {
                System.err.println(ex);
            }


    // Creates a new window that will display the screenshot
    Stage imageStage = new Stage();

    Parent newWindow = FXMLLoader.load(getClass().getResource("screenshotWindow.fxml"));
    imageStage.setTitle("Caliber --- Current Screen Shot Window");
    imageStage.setScene(new Scene(newWindow, 800, 800));
    imageStage.show();

    // Saves the screenshot location so it can be used in the other window
    MasterVariables.image = new Image("image\" + 

您需要将您的应用程序视为 运行 在 真实 用户工作站上的东西。

真正的用户(即,不是您)不会有任何 IntelliJ 项目。 He/she 将没有任何 src 目录。所有 he/she 都将包含一个只读的 jar 文件,其中包含已编译的 类 和应用程序的静态资源、一个主目录和一个临时目录。

因此,将图像保存为用户主目录中某处的文件或临时文件,然后使用 file IO(而不是ClassLoader,它只能访问只读 jar 文件中的资源)。或者一开始就避免保存到文件中,直接保存在内存中。

如果您想知道它不起作用的原因,那是因为您正在使用 ClassLoader 加载图像。 ClassLoader 可以加载目录下的任何内容或类路径中的 jar 文件。您的 src 目录不在类路径中。