Capture screenshot in Java (AWT)

In Java there is a easy was to capture screenshots. The following captureScreenshot method will capture a screenshot of the display of your screen and save it to the disk.

public void captureScreenshot(String filename) 
   throws Exception 
{
   java.awt.Dimension size = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
   java.awt.Rectangle rectangle = new java.awt.Rectangle(size);
   java.awt.Robot robot = new java.awt.Robot();
   java.awt.image.BufferedImage image = robot.createScreenCapture(rectangle);
   javax.imageio.ImageIO.write(image, "png", new java.io.File(filename));
}

If you want to create a screenshot of a specific part of your screen, you have to modyfy the rectangle. You can do this with rectangle .setBounds(int x, int y, int width, int height).

Rectangle API: http://docs.oracle.com/

Note: This will need “java.awt”. So you cannot run this code on Android devices, because there is no java.awt package available. Also note, that you have to run a X-Server on linux to execute this. If you try to execute this on a linux server without X-Server, you will not be able to capture screenshot of your terminal.
On Windows this is not a problem. The capture screenshot method will work on windows even if you are not the Administrator.