Get string value from clipboard in Java

Description

The following code shows how to get string value from clipboard.

Example


// w ww  . j  a v  a 2  s .  c om
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;

public class Main {
  public static void main(String[] argv) {
    System.out.println(getClipboard());
  }

  public static String getClipboard() {
    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    try {
      if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        String text = (String) t.getTransferData(DataFlavor.stringFlavor);

        return text.trim();
      }
    } catch (Exception e) {
    }
    return "";
  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    Development »




Java Algorithms
Java Clipboard
Java Compiler
Java Desktop
Java Virtual Machine
Java Math
OS
Random
Java Robot
Java RuntimeMXBean
Java Timer
Java UUID
Java Internationalization