标签:Java
1.1 编码表的概述1.2.2 案例代码十一
package com.itheima_09;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/*
* 编码表:把计算机底层的二进制数据转换成我们能看到的字符
* ASCII
*
* GB2312 --- GBK
* Unicode 所有的字符都占2个字节
* UTF-8 长度可变的码表
*
* ANSI:本地编码表 gbk
* Java中的字符串默认使用的ANSI(gbk)
*
* 乱码:编码保持前后一致即可解决
*
*/
public class EncoderDemo {
public static void main(String[] args) throws IOException {
//method();
FileInputStream fis = new FileInputStream("a.txt");
byte[] bys = new byte[1024];
int len = fis.read(bys);
//System.out.println(new String(bys,0,len));
System.out.println(new String(bys,0,len,"UTF-8"));
}
private static void method() throws UnsupportedEncodingException, FileNotFoundException, IOException {
String s = "高薪就业";
//byte[] bys = s.getBytes();//通过默认编码转换成数组
byte[] bys = s.getBytes("UTF-8");
FileOutputStream fos = new FileOutputStream("a.txt");
fos.write(bys);
fos.close();
}
}
1.3 字符流中的编码
1.3.1 常见对象
InputStreamReader(InputStream in, CharsetDecoder dec) 创建使用给定字符集×××的 InputStreamReader
OutputStreamWriter(OutputStream out, CharsetEncoder enc) 创建使用给定字符集编码器的 OutputStreamWriter
1.3.2 案例代码十二
package com.itheima_09;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
/*
* 字符流中的编码
*
* 字符流 = 字节流 + 编码
*
*/
public class EncoderDemo2 {
public static void main(String[] args) throws IOException {
//method();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("b.txt"),"UTF-8");
//OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("b.txt"));
String s = "迎娶白富美";
osw.write(s);
osw.close();
}
private static void method() throws IOException, UnsupportedEncodingException {
FileWriter fw = new FileWriter("b.txt");
String s = "月薪过万";
byte[] bys = s.getBytes("UTF-8");
//fw.write(s);
fw.write(new String(bys));
fw.close();
}
}
标签:Java
原文地址:http://blog.51cto.com/13517854/2105264