更新时间:2023-11-14 23:08:46
要访问剪贴板,可以使用有 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;