频道栏目
首页 > 资讯 > 代码收藏 > 正文

Java GBK,UTF-8编码

16-01-09        来源:[db:作者]  
收藏   我要投稿

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都支持中文编码

有兴趣的可以去试一下:在记事本中写入“联通”二字,保存后再打开会出现什么现象,为什么呢?

 

相关TAG标签
上一篇:PHP图片上传解决方案
下一篇:ie与火狐登录的有关问题,大神求解。
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站