0

我正在制作一个截取屏幕截图的程序,我想拥有它,以便我有一个带有 actionlistener 的 JButton,当按下它时,它将图像保存到某个文件夹中,如果该文件夹尚不存在,它就会生成。

这是我认为我应该做的:

@Override
public void actionPerformed(ActionEvent arg0) {
    File dir = new File("C://SnippingTool+/" +  date.getDay());
    dir.mkdirs();
try {
    ImageIO.write(shot, "JPG", dir);
} catch (IOException e) {
    e.printStackTrace();
}

    }

});

我认为这与我File dir = new File有关,而且我没有保存到正确的地方。

这是我Robot的截图:

try {
shot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    } catch (HeadlessException e1) {
        e1.printStackTrace();
    } catch (AWTException e1) {
        e1.printStackTrace();
    }
4

2 回答 2

1

正如我所看到的,问题在于这两行......

File dir = new File("C://SnippingTool+/" +  date.getDay());
dir.mkdirs();

现在这意味着您尝试写入的输出是一个目录,当ImageIO需要一个文件时,这将失败......

而是尝试类似...

File output = new File("C://SnippingTool+/" +  date.getDay() + ".jpg");
File dir = output.getParentFile();
if (dir.exists() || dir.mkdirs()) {
    try {
        ImageIO.write(shot, "JPG", output);
    } catch (IOException e) {
        e.printStackTrace();
    }    
} else {
    System.out.println("Bad Path - " + dir);
}
于 2013-07-13T01:01:14.610 回答
0

回应您的评论:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
    at main$2$2.actionPerformed(main.java:148) 

那是在:

File output = new File(System.getProperty("user.home") + 
                       date.getDay() + ".jpg"); 

(我将“C:\”更改为 System.getProperty("User.home"))。

该行中只有两个可能的 NPE 原因(为便于阅读而包装):

  • 如果System.getProperty找不到命名属性,它将返回一个null. 现在该"user.home"属性应该存在......但"User.home"几乎可以肯定不存在。(属性名称区分大小写!!)

  • 如果datenulldate.getDay()返回null。我们不知道您是如何初始化date的……甚至不知道它是什么类型。(虽然Date会是一个很好的猜测......)


"user.home"财产和财产都"user.dir"可以工作……尽管它们的含义不同。

于 2013-07-14T05:12:05.773 回答