检查字符串是否是用 Java 编码的有效 UTF-8 [英] Check if a String is valid UTF-8 encoded in Java

查看:32
本文介绍了检查字符串是否是用 Java 编码的有效 UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字符串是否为有效的 UTF-8 格式?

How can I check if a string is in valid UTF-8 format?

推荐答案

只能检查字节数据.如果你构造了一个字符串,那么它在内部已经是 UTF-16 了.

Only byte data can be checked. If you constructed a String then its already in UTF-16 internally.

字节数组可以进行 UTF-8 编码.

Also only byte arrays can be UTF-8 encoded.

这是一个常见的 UTF-8 转换案例.

Here is a common case of UTF-8 conversions.

String myString = "u0048u0065u006Cu006Cu006F World";
System.out.println(myString);
byte[] myBytes = null;

try 
{
    myBytes = myString.getBytes("UTF-8");
} 
catch (UnsupportedEncodingException e)
{
    e.printStackTrace();
    System.exit(-1);
}

for (int i=0; i < myBytes.length; i++) {
    System.out.println(myBytes[i]);
}

如果您不知道字节数组的编码,juniversalchardet 是一个库帮助您检测它.

If you don't know the encoding of your byte array, juniversalchardet is a library to help you detect it.

这篇关于检查字符串是否是用 Java 编码的有效 UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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