importjava.nio.charset.StandardCharsets;publicclassStringToUtf8Example{publicstaticvoidmain(String[]args){StringoriginalString="hello, 你好! 😊";// 将字符串转换为UTF-8字节数组byte[]utf8Bytes=originalString.getBytes(
下面是一个完整的示例,演示了如何将字符串转换为UTF-8编码,并通过网络发送。 importjava.io.IOException;importjava.io.OutputStream;importjava.net.Socket;publicclassUtf8StringExample{publicstaticvoidmain(String[]args){StringoriginalString="你好,世界!";byte[]utf8Bytes=originalString.getBytes(StandardCharsets.U...
GBK包含全部中文字符,是国家编码,通用性比UTF8差,不过UTF8占用的数据库比GBK大。 Java中String和byte[]间的转换 byte[] byteArray = {'w'};String str = new String(byteArray);byte[] qun = str.getBytes();String coding = "GBK";String ceshi = "张继";byte re[] = ceshi.toString().getBytes(...
publicclassTestCharset {public static void main(String[]args) {newTestCharset().execute();}privatevoid execute(){String s ="Hello!你好!";byte[]bytesISO8859 = null;byte[]bytesGBK = null;try{bytesISO8859 = s.getBytes("iso-8859-1");bytesGBK = s.getBytes("GBK");} catch (java.io.Unsu...
1、string 转 byte[] String inStr="hello world"; byte[] bytes= inStr.getBytes(StandardCharsets.UTF_8); 2、byte[] 转 string String outSrt = new String(bytes, StandardCharsets.UTF_8); 注意:一定要注意转换时的编码问题,尤其byte转string时一定要指定编码,否则很容易出现中文乱码问题。
public static void main(String[] args) throws IOException { Charset utf8 = StandardCharsets.UTF_8; Charset gbk2312 = Charset.forName("GB2312"); //将某段文字以gb2312编码后得到的字节数组,再以utf-8进行解码得到的文字是乱码,并且这段乱码中丢失了信息。
Java的String和char类型,在内存中默认是采用的Unicode编码,但我们可以采用新的编码对原有字符串进行重新编码,这主要是通过"字符串".getBytes(编码名称)的方式实现。在转换编码格式后,原有的字符串或字符,就不再是char类型了,而是byte数组类型。 但当我们采用GBK或GB2312编码,对原有字符进行编码得到新的字节数组后,...
public static int stringToUtf8(String s, byte[] buf, int offset) { if (s == null) { return 0; } int length = s.length(); int startOffset = offset; for (int i = 0; i < length; i++) { int c = s.charAt(i); if (c < 0x80) { ...
1.string 转 byte[]byte[] midbytes=isoString.getBytes("UTF8");//为UTF8编码 byte[] isoret = srt2.getBytes("ISO-8859-1");//为ISO-8859-1编码 其中ISO-8859-1为单字节的编码 2.byte[]转string String isoString = new String(bytes,"ISO-8859-1");String srt2=new String(mid...
Java的String和char类型,在内存中默认是采用的Unicode编码,但我们可以采用新的编码对原有字符串进行重新编码,这主要是通过"字符串".getBytes(编码名称)的方式实现。在转换编码格式后,原有的字符串或字符,就不再是char类型了,而是byte数组类型。 但当我们采用GBK或GB2312编码,对原有字符进行编码得到新的字节数组后,...