获取剪贴板字符串编码(java) [英] Get Clipboard String Encoding (java)

查看:128
本文介绍了获取剪贴板字符串编码(java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以使用Java获取剪贴板上字符串的编码类型。 (我会提供更多详细信息,但是问题很简单)。

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).

例如。我进入一个unicode程序,复制文本,使用Java程序对其进行解密,然后Java程序吐出 UTF-16

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

推荐答案

要访问剪贴板,可以使用 datatransfer
要检测字符集,可以使用 ICU项目中的 CharsetDetector

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

这是代码:

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;

这篇关于获取剪贴板字符串编码(java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆