如何在Java中将字符串转换为UTF8字节数组 [英] How to convert Strings to and from UTF8 byte arrays in Java

查看:184
本文介绍了如何在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?

推荐答案

从字符串转换为byte []:

Convert from String to byte[]:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");

从byte []转换为字符串:

Convert from byte[] to String:

byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, "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屋!

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