Search code examples
javascreenshotawtrobot

ImageIO does not save screenshots


I am trying to get a screenshot of my desktop and save it in specific folder, for this purpose, I wrote following method:

class Test(){
     public static String screenshot(String outDir){
            try {
                Robot robot = new Robot();
                String format = ".png";
                String fileName = String.valueOf(System.currentTimeMillis()) + format;
                Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
                BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
                ImageIO.write(screenFullImage, format, new File(outDir + fileName));
                System.out.println("Success");
                return outDir + fileName;
            } catch (AWTException | IOException e) {
                e.printStackTrace();
            }

            return null;
        }
}

I was planning to use the code like so:

Test.screenshot("C:\\temp\\");

So the magic is it does not write the screenshot file in the specific folder, but if I remove file extension and explicitly hardcode the name of the file it writes the result.

However, this code works:

public static String screenshot(){
        try {
            Robot robot = new Robot();
            String format = "jpg";
            String fileName = "XXX." + format;
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
            ImageIO.write(screenFullImage, format, new File("C:\\temp\\" + fileName));
            System.out.println("Success");
            return outDir + fileName;
        } catch (AWTException | IOException e) {
            e.printStackTrace();
        }

        return null;
    }

What am I doing wrong here?


Solution

  • I have seen the javadoc. The problem is about the formatName, as doc say: formatName - a String containg the informal name of the format. => means that your format should only contain name, not include the dot (.). So that's why your hardcode run because your hardcode using the correct formatName