Get readable text only from clipboard

拟墨画扇 提交于 2019-11-27 03:53:14
Dragon8
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 a problem of the programm which puts the data in the clipboard.

Mihir Patel

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 "";
}

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!