PrintStream,PrintWriter,Scanner添加了带Charset参数的构造方法,通过Charset可以指定IO流操作文本时的编码。
image-20211204220850340.png
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
public class Demo04 {
public static void main(String[] args) throws IOException {
test01();
test02();
}
// 使用指定的GBK编码打印数据
private static void test02() throws IOException {
PrintStream ps = new PrintStream("JDK10\\files\\ps2.txt",Charset.forName("GBK"));
ps.println("你好");
ps.close();
}
// 使用IDEA默认的UTF-8编码打印数据
private static void test01() throws FileNotFoundException {
PrintStream ps = new PrintStream("JDK10\\files\\ps1.txt");
ps.println("你好");
ps.close();
}
}
小结
在JDK10中给IO流中的很多类都添加了带Charset参数的方法,比如PrintStream,PrintWriter,Scanner。通过Charset 可以指定编码来操作文本。Charset是一个抽象类,我们不能直接创建对象,需要使用Charset的静态方法 forName("编码"),返回Charset的子类实例。
ByteArrayOutputStream新增toString方法
image-20211204221053822.png
JDK10给 ByteArrayOutputStream 新增重载 toString(Charset charset) 方法,通过指定的字符集编码字节,将缓冲区的内容转换为字符串。
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
public class Demo06 {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "你好中国";
ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes("GBK"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
System.out.println(bos.toString());
System.out.println(bos.toString("GBK"));
}
}