Explore Java

Be Social. Be Updated.

  • Stumble
  •   
  •   

Get Data from Clipboard in Java



An example on getting and printing a string from system clipboard in Java in just 2 statements.


Example



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.

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).


0 comments:

About This Blog

This blog contains Java Tutorials, Code Samples,demonstrating several concepts in Java. All the code samples are well tested by a team of experts and hence there will be no programmatical errors. We are seamlessly thriving in making the tutorials easier for beginners.

About the Author

was a software and technology enthusiast. He is a 12th grade student and a part time blogger with extreme love in Java programming.Follow him on Google+ and Twitter or befriend him on Facebook and also on