如何在 Java 中将字符串与 UTF8 字节数组相互转换 [英] How to convert Strings to and from UTF8 byte arrays in Java
本文介绍了如何在 Java 中将字符串与 UTF8 字节数组相互转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中,我有一个字符串,我想将它编码为字节数组(UTF8 或其他编码).或者,我有一个字节数组(采用某种已知编码),我想将其转换为 Java 字符串.我如何进行这些转换?
In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?
推荐答案
从字符串转换为字节[]:
Convert from String to byte[]:
String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
从字节[]转换为字符串:
Convert from byte[] to String:
byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);
当然,您应该使用正确的编码名称.我的示例使用了 US-ASCII 和 UTF-8,这两种最常见的编码.
You should, of course, use the correct encoding name. My examples used US-ASCII and UTF-8, the two most common encodings.
这篇关于如何在 Java 中将字符串与 UTF8 字节数组相互转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文