我正在尝试获取桌面的屏幕截图并将其保存在特定文件夹中,为此,我编写了以下方法:
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;
}
}
我打算像这样使用代码:
Test.screenshot("C:\\temp\\");
所以神奇的是它不会在特定文件夹中写入屏幕截图文件,但如果我删除文件扩展名并显式硬编码文件名,则会写入结果。
但是,此代码有效:
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;
}
我在这里做错了什么?
答案 0 :(得分:1)
我见过here。问题与formatName
有关,正如文档所述:formatName - a String containg the informal name of the format.
=>表示您的格式应仅包含名称,不包括点(。)。这就是为什么您的硬编码会运行,因为您的硬编码使用了正确的formatName