How To Set And Get System Clipboard Contents In Java

The clipboard is a software facility that can be used for short-term data storage and/or data transfer between documents or applications, via copy and paste operations. It is most commonly a part of a GUI environment and is usually implemented as an anonymous, temporary block of memory that can be accessed from most or all programs within the environment via defined programming interfaces. A typical application accesses clipboard functionality by mapping user input (keybindings, menu selections, etc.) to these interfaces. [Wikipedia]

The following tutorial demonstrate how to read the content of a clipboard or set data in the clipboard.

package com.kushal.utils;

/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modfiied On 31st July 2009
 */
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

public class SystemClipboardDataManipulate {

	/**
	 * When you do a cut or copy of text in the operating system, the text is
	 * stored in the clipboard.
	 *
	 * The following method returns the content that is currently in the
	 * clipboard.
	 *
	 */
	public static String getClipboardData() {
		String clipboardText;
		Transferable trans = Toolkit.getDefaultToolkit().getSystemClipboard()
				.getContents(null);

		try {
			if (trans != null
					&& trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
				clipboardText = (String) trans
						.getTransferData(DataFlavor.stringFlavor);
				return clipboardText;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * This method will set any parameter string to the system's clipboard.
	 */
	public static void setClipboardData(String string) {
		StringSelection stringSelection = new StringSelection(string);
		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
				stringSelection, null);
	}

	/**
	 * Testing the clipboard set and get methods.
	 */
	public static void main(String[] args) {

		/**
		 * If something is already there in the clipboard, printing the value.
		 */
		System.out.println(getClipboardData());

		/**
		 * Setting our own clipboard data
		 */
		setClipboardData("Sanjaal.com/java");

		/**
		 * Printing the Clipboard Data We Just Set.
		 */
		System.out.println(getClipboardData());

	}

}


Here is the output (The first line depends on what is there in your system clipboard).
Most environments support a single clipboard transaction. Each cut or copy overwrites the previous contents.
Sanjaal.com/java