问题
I'm making a program that takes a screenshot and I want to have it so that i have a JButton with an actionlistener that when pressed it saves the image to a certain folder that if does not already exists it makes.
here is what I thought I should do:
@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();
}
}
});
I think it has something to do with my File dir = new File and that I am not saving to to the right place.
Here is my Robot taking a screenshot:
try {
shot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
} catch (HeadlessException e1) {
e1.printStackTrace();
} catch (AWTException e1) {
e1.printStackTrace();
}
回答1:
The problem, as I see it is with these two lines...
File dir = new File("C://SnippingTool+/" + date.getDay());
dir.mkdirs();
This now means that the output you are trying to write to is a directory, when ImageIO is expecting a file, this will fail...
Instead try something like...
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);
}
回答2:
In response to your comment:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at main$2$2.actionPerformed(main.java:148)That is at the:
File output = new File(System.getProperty("user.home") + date.getDay() + ".jpg");(I changed the "C:\" to System.getProperty("User.home")).
There are only two possible causes of an NPE in that line (wrapped for readability):
If
System.getPropertycannot find the named property, it will return anull. Now the"user.home"property should exist ... but"User.home"almost certainly does NOT exist. (Property names are case sensitive!!)If
dateisnullordate.getDay()returnsnull. We don't know how you initializeddate... or even what type it is. (ThoughDatewould be a good guess ...)
Both the "user.home" property and the "user.dir" property would work ... though they mean different things.
来源:https://stackoverflow.com/questions/17625976/how-to-save-my-screenshot-in-java