Search code examples
javaimagetimescreenshot

Adding Time to an Image


I'm trying to take a screenshot using the following code

public void TakeScreenShot() {
    String ScreenPrefix = "Screenshot-";
    String Time = getTime();
        try {
            File ScreenName = new File(ScreenPrefix+Time+".png");
                BufferedImage image = new Robot().createScreenCapture(new Rectangle(getGameScreen()));
                ImageIO.write(image, "PNG", new File(System.getProperty("user.home") + "\\Desktop\\ScreenShots\\"+ScreenName));
                JOptionPane.showMessageDialog(null, ScreenName+".png has been saved to your desktop", "Console", JOptionPane.PLAIN_MESSAGE);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

if I use the getTime(); method I get the following error:

java.io.FileNotFoundException: C:\Users\Evan\Desktop\ScreenShots\Screenshot-19:30:14 (The filename, directory name, or volume label syntax is incorrect)

but if I change

File ScreenName = new File(ScreenPrefix+Time);

to

File ScreenName = new File(ScreenPrefix);

It works perfectly fine, it just doesn't include the time the screenshot was taken.

if anyone knows how to make the code create the file "Screenshot-Hour:Minute:Seconds" and is willing to share, it would be very apprieciated

(if you can tell me why I'm getting this error it'd be quite helpful as well)

If you need it, here's my getTime() method:

public static String GetTime() {
    Calendar cal = Calendar.getInstance();
    cal.getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    return sdf.format(cal.getTime());
}

I do have the path "C:\Users\Evan\Desktop\Screenshots" as well, so I don't know why it's telling me I don't when I try to include the time, because it works fine without it


Solution

  • You need to edit the name of the file being saved such that it does not include special characters.

    That error is saying the file you're trying to create is invalid.