Get readable text only from clipboard
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 DataFlavor
s?
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.
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 "";
}