Get Clipboard String Encoding (java)

大城市里の小女人 提交于 2020-02-04 09:28:33

问题


I was wondering if theres a way to use Java to get the encoding type of a string on the clipboard. (I'd give more details but the question is fairly straight forward).

Ex. I go into a unicode program, copy text, use the Java program to decipher it, and the java program spits out "UTF-16"


回答1:


To access the clipboard, you can use the awt datatransfer classes. To detect the charset, you can use the CharsetDetector from ICU project.

Here is the code :

public static String getClipboardCharset () throws UnsupportedCharsetException, UnsupportedFlavorException, IOException {
    String clipText = null;
    final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    final Transferable contents = clipboard.getContents(null);
    if ((contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor))
        clipText = (String) contents.getTransferData(DataFlavor.stringFlavor);

    if (contents!=null && clipText!=null) {
        final CharsetDetector cd = new CharsetDetector();
        cd.setText(clipText.getBytes());
        final CharsetMatch cm = cd.detect();

        if (cm != null)
            return cm.getName();
    }

    throw new UnsupportedCharsetException("Unknown");
}

Here are the imports needed :

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.nio.charset.UnsupportedCharsetException;

import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;


来源:https://stackoverflow.com/questions/17034956/get-clipboard-string-encoding-java

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