80

I want to set the user's clipboard to a string in a Java console application. Any ideas?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
clone1018
  • 1,177
  • 2
  • 9
  • 11

5 Answers5

146

Use the Toolkit to get the system clipboard. Create a StringSelection with the String and add it to the Clipboard.

Simplified:

StringSelection selection = new StringSelection(theString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
user85421
  • 28,490
  • 10
  • 64
  • 86
  • It didn't work for me, the clipboard was cleared. I'm using Linux. – Searene Apr 14 '19 at 10:24
  • it should, maybe consider the second comment on original question, or rado's [answer](https://stackoverflow.com/a/11059985/85421) below – user85421 Apr 14 '19 at 14:35
33

Here is a simple SSCCE to accomplish this:

import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;

class ClipboardTest
{
    public static void main(String[] args)
        throws UnsupportedFlavorException, IOException
    {
        Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
        StringSelection testData;

        //  Add some test data

        if (args.length > 0)
            testData = new StringSelection( args[0] );
        else
            testData = new StringSelection( "Test Data" );

        c.setContents(testData, testData);

        //  Get clipboard contents, as a String

        Transferable t = c.getContents( null );

        if ( t.isDataFlavorSupported(DataFlavor.stringFlavor) )
        {
            Object o = t.getTransferData( DataFlavor.stringFlavor );
            String data = (String)t.getTransferData( DataFlavor.stringFlavor );
            System.out.println( "Clipboard contents: " + data );
        }

        System.exit(0);
    }
}
ryvantage
  • 12,309
  • 14
  • 59
  • 104
camickr
  • 316,400
  • 19
  • 155
  • 279
9

For anyone still stumbling upon this post searching for the JavaFX way to accomplish this, here you go:

ClipboardContent content = new ClipboardContent();
content.putString("Some text");
content.putHtml("<b>Bold</b> text");
Clipboard.getSystemClipboard().setContent(content);

For further information, read the documentation.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
xeruf
  • 1,924
  • 1
  • 17
  • 39
3

If you are on Linux and using OpenJDK, it will not work. You must use the Sun JDK on Linux for it to work.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
rado
  • 3,896
  • 3
  • 29
  • 24
1

In Linux with xclip:

Runtime run = Runtime.getRuntime();
Process p = null;
String str = "hello";
try {
        p = run.exec(new String[]{"sh", "-c", "echo " + str + " | xclip -selection clipboard"});
}
catch (Exception e) {
    System.out.println(e);
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124