package io3;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class Demo2 {
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
// 编码
String str = "AB中国";
// UTF-8
byte[] utf = str.getBytes("UTF-8");
System.out.println(Arrays.toString(utf));
// [65, 66, -28, -72, -83, -27, -101, -67]
// GBK
byte[] gbk = str.getBytes("GBK");
System.out.println(Arrays.toString(gbk));
// [65, 66, -42, -48, -71, -6]
// 把一个字符串写到文件里面,设计这个字符串的编码
// write(byte[]):把byte[]里面的内容直接写入到文件里面
// read(byte[]):把读取内容存放到byte[]里面
FileOutputStream out = new FileOutputStream("src/test2.txt");
String str2 = "HI,快放学了,吃饭,下午继续上课";
byte[] str2Bytes =str2.getBytes("GBK");
out.write(str2Bytes);
out.close();
FileInputStream in = new FileInputStream("src/test2.txt");
byte[] readBytes = new byte[str2Bytes.length];
in.read(readBytes);
// readBytes:保存就是文本的bytebyte内容
// String(byte[],"编码级"):可以把一个byte[]数组
// 直接转化为按照"编码级"的字符串
String gbk1 = new String(readBytes,"UTF-8");
// 注意乱码问题
System.out.println(gbk1);
}
}
阅读(1041) | 评论(0) | 转发(0) |