Copying to the clipboard in Java [duplicate]
Asked Answered
R

5

83

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

Retrusion answered 28/8, 2010 at 18:32 Comment(2)
I tried using AWT to no avail.Retrusion
then show what you've tried and tell us what exactly didn't workPutrid
H
152

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);
Hornwort answered 28/8, 2010 at 18:54 Comment(2)
It didn't work for me, the clipboard was cleared. I'm using Linux.Unprovided
it should, maybe consider the second comment on original question, or rado's answer belowHornwort
E
38

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);
    }
}
Ecstatic answered 28/8, 2010 at 19:44 Comment(0)
A
14

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.

Augustaaugustan answered 10/1, 2018 at 11:58 Comment(0)
W
2

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

Weisbart answered 16/6, 2012 at 1:12 Comment(3)
Why? do you have more information about it? A bug report? You could get some reputation ;) https://mcmap.net/q/138063/-copying-to-global-clipboard-does-not-work-with-java-in-ubuntu/194609Burgonet
What will not work? Is this a response to one of the other answers?Footstep
This is very wrong. Sun JDK isd openjdk build as everything else, and clipoabrd on linux, including java as client, works fineTottering
S
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);
}
Shrink answered 24/7, 2017 at 1:41 Comment(4)
What if the string contains end-of-line characters? Will it work then?Footstep
that really defeats the idea of a multi platform programming language..Analogy
This is lacking any kind of sanitation. Please don't use this in production code. If someone copies the string " rm -rf $HOME, you've just deleted their home directory. Also, I believe Ubuntu doesn't come with xclip by default.Got
@Got You're right. That's why I came up with the following solution: String text = "text_to_copy_to_clipboard"; ProcessBuilder pb = new ProcessBuilder("xclip", "-selection", "clipboard"); BufferedWriter bw = null; try { Process process = pb.start(); bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); bw.write(text); } finally {if (bw != null) bw.close();}Loggerhead

© 2022 - 2024 — McMap. All rights reserved.