2016-05-17 196 views
0

目前,我正在尝试使用Robot功能创建screencapture。现在我已经可以使用按钮进行截图并将其保存为图像形式。现在我想要做同样的事情,但我想生成不同的文件名,例如screenshot1.png,screenshot2.png。我可以知道如何使用for循环随机生成数字。Java:为机器人screencapture生成随机文件名

这是我当前的Java工作代码:

private void jbtnCaptureActionPerformed(java.awt.event.ActionEvent evt) { 
     // TODO add your handling code here: 
     try { 
      Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); 
      Robot ro = new Robot(); 
      BufferedImage capture = ro.createScreenCapture(screenRect); 
      File f; 
      f = new File("myimage1.jpg");       
      ImageIO.write(capture, "jpg", f); 
      System.out.println("Success"); 



     } catch (Exception e){ 
      System.out.println("Unable to capture the screen" + e); 
     } 

} 

有人可以帮助我在此。提前致谢。

+1

为什么你想让它是“随机的”?随机意味着你无法通过文件名告诉屏幕截图的顺序,随机也意味着你可能有重复的文件名 –

+0

所以有没有更好的方法来做到这一点@AdrianShum?因为我需要显示多个图像用于comapring的目的。 – anonymous5671

+1

难道你不能只在应用程序中保留一个正在运行的序列号吗? –

回答

2

我想每个屏幕捕捉是由某种按钮点击右键(而不是循环中的多个捕获)触发?

最直接的办法就是保持一个整数为文件名的时候运行序列:

private void jbtnCaptureActionPerformed(java.awt.event.ActionEvent evt) { 
    ..... 
      File f = new File("myimage" + (this.filenameSeq++) + .jpg"); 
    ...... 
} 

而且,如果不产生你的捕捉非常频繁(如几百个文件每一秒的) ,还有另一种方法可以避免保持正在运行的顺序。您可以根据当前时间生成文件名,并检查文件是否存在。如果存在,请继续附加序列号,直到找到文件不存在。在伪代码:

String filenameBase = "myImage"; 
String currentTimestamp = new SimpleDateFormat("yyyymmddHHMMss").format(now()); 
File f = new File(filenameBase + currentTimestamp + ".png"); 
for (int i = 0; f.exists(); i++) { 
    f = new File(filenameBase + currentTimestamp + "-" + i + ".png"); 
} 
// so here, you will have a filename which is not yet exists in your filessystem 
+0

它显示'无法格式化给定的对象作为日期' – anonymous5671

+1

我说它是伪代码!它只是给你的想法,而不是瞄准你复制和粘贴! –

0

只需使用一个伪随机生成:

Random rnd = new Random(); 
String filename = "screenshot" + rnd.nextInt() + ".png"; 

当然,初始化函数外的伪随机生成,并保持它从一个屏幕截图到另一个。

0

为什么不能动态地检查文件名的存在[X] .JPG,递增数,直到没有文件存在同名..

public File getUniqueFile(String name) { 
    int i=1; 
    File file; 
    do { 
     file = new File(name + (i++) + ".jpg"); 
    } while (file.exists()); 
    return file; 
} 
+0

没有注意到阿德里安给出了同样的答案 – slipperyseal