Get Data from Clipboard in Java

Here is how to get text from clipboard in Java and print it in two simple statements.

import java.awt.*;
import java.awt.datatransfer.*;
class SystemClipboard
{
public static void main(String args[]) throws Exception
{

// Create a Clipboard object using getSystemClipboard() method
Clipboard c=Toolkit.getDefaultToolkit().getSystemClipboard();

// Get data stored in the clipboard that is in the form of a string (text)
System.out.println(c.getData(DataFlavor.stringFlavor));

}
}

Explanation

java.awt.*: Contains Toolkit class.

java.awt.datatransfer.*: Contains Clipboard class.

Exception: UnsupportedFlavorException is thrown.

Flavor: Nothing but the type of the data. We need to specify it in order to get what type of data we want. For example, if clipboard contains an image, then it is imageFlavor or if it contains only characters then stringFlavor. These are constants however present in the java.awt.datatransfer.DataFlavor class. Here is how to paste image from clipboard in Java

Toolkit.getDefaultToolkit().getSystemClipboard(): Toolkit class has a public static method getDefaultToolkit() which returns an instance of the java.awt.Toolkit class which is useful for calling the normal public method getSystemClipboard(). This method returns the java.awt.datatransfer.Clipboard object which will further be used to get data from the system clipboard.

c.getData(DataFlavor.stringFlavor): Get the data in the clipboard that is just in the form of general characters. An exception is thrown if either the clipboard is empty or contains other than string (for example an image).

Also see my post on AWT Tutorial in Java

No comments: