我在 JSP Web 应用程序中添加了一个功能,用户可以对他正在查看的页面进行屏幕截图,并将图像保存到桌面,当我拍摄另一个屏幕截图时,它会覆盖以前的图像。有什么方法可以递增,以便将其另存为图像,如果我拍摄另一个屏幕截图,它将另存为 image1、image2 等。
执行此任务的代码是
try {
Robot robot = new Robot();
BufferedImage screenShot = robot
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
String home = System.getProperty("user.home");
ImageIO.write(screenShot, "JPG", new File(home + "\\Desktop\\i.jpg"));
} catch (IOException ex) {
System.out.println(ex.toString());
}
最佳答案
为此,您首先需要检查桌面中是否已存在同名文件:
boolean check = new File(directory, temp).exists();
如果 booelan 检查为 true,则意味着该文件已存在,并且具有相同的名称。然后,您可以根据需要更改第二个文件的名称(例如,向其中添加数字)!
此外,如果用户想要将文件另存为image3,并且已经有一个以这种方式调用的文件,您可以像这样更改它:
int num;
try {
num = Integer.parseInt(String.valueOf(string.substring(string.length() - 1)));
// then change the name of the file that you are saving for example, from "image4" to "image5"
} catch (exception e) {
// This means that the name of the file you are saving does not finish with a number, so you can simply proceed by adding a "1" as the last character of the string name (containing the name of the file the user wants to save)
}
关于java - 保存到桌面的图像会覆盖之前的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59106184/