70

I already know how to get plain text from the clipboard in Java, but sometimes the text is encoded in some weird DataFlavor, like when copying from Microsoft Word or from a website or even source code from Eclipse.

How to extract pure plain text from these DataFlavors?

1
  • 5
    thanks, but i am looking for a java solution, not javascript
    – clamp
    Aug 18, 2011 at 10:17

3 Answers 3

81
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

String data = (String) Toolkit.getDefaultToolkit()
                .getSystemClipboard().getData(DataFlavor.stringFlavor); 

with the getData() Method and the stringFlavor you should get plain text from the clipboard.

If there are weird text in the clipboard, I think, this should be a problem of the program which puts the data in the clipboard.

3
  • 4
    WARNING: Using the above code you can hit this known Java Bug bugs.java.com/bugdatabase/view_bug.do?bug_id=6606476 (as I did) and there is no work around. Fortunately I have Perl installed and so I can invoke a Perl script to set the clipboard contents to plain text. :( Jun 20, 2015 at 15:15
  • 1
    @SteveWaring thanks for the heads up on that odd uncatchable error. Haven't tested this yet, but I'd suggest setting the System.err stream to null and catching null pointers when attempting Dragon8's solution. (Of course don't forget to set it back to normal when done ^_^) Oct 6, 2017 at 17:01
  • is there a way to do this in headless mode browsers? Nov 24, 2020 at 4:04
4

You can use following method getting clipboard text in Java:

public String getClipBoard(){
    try {
        return (String)Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
    } catch (HeadlessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();            
    } catch (UnsupportedFlavorException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();            
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "";
}
0

First I haven't worked with clipboard but this seems intresting

From http://docstore.mik.ua/orelly/java/awt/ch16_01.htm

"To read data from the clipboard, a program calls the Transferable.getTransferData() method. If the data is represented by a DataFlavor that doesn't correspond to a Java class (for example, plainTextFlavor), getTransferData() returns an InputStream for you to read the data from."

So if you give it a class which doesn't correspont you get the InputStream and then you can read the "pure" text from the InputStream yourself.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.