Java GBK,UTF-8编码
1、GBK,UTF-8编码
注意:一般默认的是GBK编码。
- package io.dol.sn;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- public class EnCodeStream {
- public static void main(String[] args) throws IOException {
- //WriteGBK();
- WriteUTF_8();
- }
- public static void WriteGBK() throws IOException
- {
- //默认是GBK编码
- OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("gbk.txt"));
- //OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("UTF_8.txt","GBK"));
- //注意,此时产生的gbk.txt文件大小为4字节
- osw.write("海豚");
- osw.close();
- }
- public static void WriteUTF_8() throws IOException
- {
- //默认是GBK编码
- OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("UTF_8.txt"),"UTF-8");
- //注意,此时产生的UTF_8.txt文件大小为6字节
- osw.write("海豚");
- osw.close();
- }
- }
2、编码解码
用什么格式编码,就用什么格式解码;编码一次,解码一次。
- package io.dol.sn;
- import java.io.IOException;
- import java.util.Arrays;
- public class EnCodeStream {
- public static void main(String[] args) throws IOException {
- String s1 = "海豚";
- //编码:
- //以下一样,因为默认就是GBK编码
- byte[] bGbk1 = s1.getBytes();
- byte[] bGbk2 = s1.getBytes("GBK");
- //Arrays.toString()将字符数组转化为字符串
- System.out.println(Arrays.toString(bGbk1));
- System.out.println(Arrays.toString(bGbk2));
- //解码:
- String s2 = new String(bGbk1);
- String s3 = new String(bGbk2,"GBK");
- //如果用UTF-8解码,则会出现解码格式错误
- //String s4 = new String(bGbk2,"UTF-8");
- System.out.println(s2);
- System.out.println(s3);
- //这里会打印出“????”
- //System.out.println(s4);
- }
- }
3、GBK,UTF-8都支持中文编码
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。