How do I get a String from the clipboard?
Author: Deron Eriksson
Description: This Java example shows how to get a String from the clipboard.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The GetStringFromClipboard class demonstrates how to get a String from the System Clipboard. To do this, we get the System Clipboard from the Toolkit. We call getData() on the Clipboard, specifying a String 'Data Flavor'. We then display the String obtained from the Clipboard.

GetStringFromClipboard.java

package test;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;

public class GetStringFromClipboard {

	public static void main(String[] args) throws Exception {

		Toolkit toolkit = Toolkit.getDefaultToolkit();
		Clipboard clipboard = toolkit.getSystemClipboard();
		String result = (String) clipboard.getData(DataFlavor.stringFlavor);
		System.out.println("String from Clipboard:" + result);
	}

}

As a demonstration, I opened Notepad and entered some text.

Entering some text into Notepad

I selected all the text in Notepad and went to Edit → Copy to copy the text to the System Clipboard.

Copying Notepad text

After this, I ran GetStringFromClipboard. We can see that GetStringFromClipboard displayed the expected String from the Clipboard.

Results

String from Clipboard:ham and eggs