在Java中,我有一个字符串,我想将它编码为字节数组(在UTF8中,或其他编码中)。或者,我有一个字节数组(在一些已知的编码中),我想将它转换为Java String。我怎么做这些转换?
当前回答
非常晚,但我刚刚遇到了这个问题,这是我的解决方案:
private static String removeNonUtf8CompliantCharacters( final String inString ) {
if (null == inString ) return null;
byte[] byteArr = inString.getBytes();
for ( int i=0; i < byteArr.length; i++ ) {
byte ch= byteArr[i];
// remove any characters outside the valid UTF-8 range as well as all control characters
// except tabs and new lines
if ( !( (ch > 31 && ch < 253 ) || ch == '\t' || ch == '\n' || ch == '\r') ) {
byteArr[i]=' ';
}
}
return new String( byteArr );
}
其他回答
非常晚,但我刚刚遇到了这个问题,这是我的解决方案:
private static String removeNonUtf8CompliantCharacters( final String inString ) {
if (null == inString ) return null;
byte[] byteArr = inString.getBytes();
for ( int i=0; i < byteArr.length; i++ ) {
byte ch= byteArr[i];
// remove any characters outside the valid UTF-8 range as well as all control characters
// except tabs and new lines
if ( !( (ch > 31 && ch < 253 ) || ch == '\t' || ch == '\n' || ch == '\r') ) {
byteArr[i]=' ';
}
}
return new String( byteArr );
}
我的tomcat7实现是接受字符串作为ISO-8859-1;不管HTTP请求的内容类型是什么。当我试图正确解释'é'这样的字符时,下面的解决方案对我有效。
byte[] b1 = szP1.getBytes("ISO-8859-1");
System.out.println(b1.toString());
String szUT8 = new String(b1, "UTF-8");
System.out.println(szUT8);
当试图将字符串解释为US-ASCII时,字节信息没有正确解释。
b1 = szP1.getBytes("US-ASCII");
System.out.println(b1.toString());
String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");
如果你使用的是7位ASCII或ISO-8859-1(一种非常常见的格式),那么你根本不需要创建一个新的java.lang.String。简单地将字节转换为char类型的性能要好得多:
完整的工作示例:
for (byte b : new byte[] { 43, 45, (byte) 215, (byte) 247 }) {
char c = (char) b;
System.out.print(c);
}
如果你不使用扩展字符,如Ä, Æ, Å, Ç, Ï, Ê,并且可以确定唯一传输的值是前128个Unicode字符,那么这段代码也适用于UTF-8和扩展ASCII(如cp-1252)。
作为替代,可以使用Apache Commons中的StringUtils。
byte[] bytes = {(byte) 1};
String convertedString = StringUtils.newStringUtf8(bytes);
or
String myString = "example";
byte[] convertedBytes = StringUtils.getBytesUtf8(myString);
如果你有非标准的字符集,你可以相应地使用getBytesUnchecked()或newString()。
推荐文章
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 如何在POM.xml中引用环境变量?
- 如何在android中复制一个文件?
- 将整数转换为字符串,以逗号表示千
- 将JavaScript字符串中的多个空格替换为单个空格
- 接口方法的最终参数-有什么意义?
- Java中的@UniqueConstraint注释
- printf()和puts()在C语言中的区别是什么?
- 如何在清洁模式下运行eclipse ?如果我们这样做会发生什么?
- 获取java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory异常
- Java中的正则表达式命名组
- c#和Java的主要区别是什么?
- 什么是NullPointerException,我如何修复它?
- 在Java中使用“final”修饰符