Java 字符转码之UTF 您所在的位置:网站首页 java字符转成字符串 Java 字符转码之UTF

Java 字符转码之UTF

2024-07-01 00:45| 来源: 网络整理| 查看: 265

java跟python类似的做法,在java中字符串的编码是java修改过的一种Unicode编码,所以看到java中的字符串,心理要默念这个东西是java修改过的一种Unicode编码的编码。

package string; import java.nio.charset.Charset; public class UTF82GBK { public static void main(String[] args) throws Exception { //系统的默认编码是GBK System.out.println("Default Charset=" + Charset.defaultCharset()); String t = "hfjkds中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国hfsdkj fjldsajflkdsjaflkdsjalf sfdsfadas"; //思路:先转为Unicode,然后转为GBK String utf8 = new String(t.getBytes( "UTF-8")); //等同于: // String utf8 = new String(t.getBytes( "UTF-8"),Charset.defaultCharset()); System.out.println(utf8); String unicode = new String(utf8.getBytes(),"UTF-8"); //等同于: // String unicode = new String(utf8.getBytes(Charset.defaultCharset()),"UTF-8"); System.out.println(unicode); String gbk = new String(unicode.getBytes("GBK")); //等同于: // String gbk = new String(unicode.getBytes("GBK"),Charset.defaultCharset()); System.out.println(gbk); } }

 

 

 

package com.mkyong; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; public class UTF8ToGBK { public static void main(String[] args) throws Exception { File fileDir = new File("/home/user/Desktop/Unsaved Document 1"); BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream(fileDir), "UTF-8")); String str; while ((str = in.readLine()) != null) { System.out.println(str);// java内部只有unicode编码 所以str是unicode编码 String str2 = new String(str.getBytes("GBK"), "GBK");// str.getBytes("GBK")是gbk编码,但是str2是unicode编码 System.out.println(str2); } in.close(); } }

 问题的关键是new String(xxx.getBytes("gbk"), "gbk")这句话是什么意思,xxx.getBytes("gbk")得到的数组编码是GBK,因此必须必须告诉java:我传给你的数组是gbk编码的,你在转换成你内部的编码的时候记得要进行一些处理,new String(xxx.getBytes("gbk"), "gbk"),这句话第二个“gbk”是告诉java传递给它的是gbk编码的字符串。

String fullStr = new String(str.getBytes("UTF-8"), "UTF-8");//正常 String fullStr2 = new String(str.getBytes("UTF-8"), "GBK");//不正常,java内置的编码->utf8 被当成GBK编码转换成java内置的编码

看一下jdk文档是怎么说的

public String(byte[] bytes, Charset charset)

Constructs a new String by decoding the specified array of bytes using the specified charset.

那现在的问题就是,我怎么在String中持有GBK编码的东西呢?

String str3 = new String(str.getBytes("GBK"),"ISO-8859-1"); System.out.println(new String(str3.getBytes("ISO-8859-1"),"GBK"));

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有