您的位置 首页 java

java10 新特性 IO流大家族添加Charset参数的方法

PrintStream,PrintWriter,Scanner添加了带Charset参数的 构造方法 ,通过 Charset 可以指定IO流操作文本时的编码。

 import java.io. File NotFound Exception ;
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方法

JDK10给 ByteArrayOutputStream 新增重载 toString(Charset charset) 方法,通过指定的 字符集 编码字节,将缓冲区的内容转换为字符串。

 import java.io.ByteArray InputStream ;
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"));
    }
}
  

文章来源:智云一二三科技

文章标题:java10 新特性 IO流大家族添加Charset参数的方法

文章地址:https://www.zhihuclub.com/188084.shtml

关于作者: 智云科技

热门文章

网站地图