java字符转换流

OutPutStreamWrite是字符通向字节流的桥梁

  • 构造方法:

    • OutPutStreamWrite(OutPutStream out)
    • OutPutStreamWrite(OutPutStream out, String chatsetName)
      • 参数
        • OutPutStream out字节输出流,可以用来写转换之后的字节到文件中
        • String charsetName 指定的编码表名称,不区分大小写,可以是utf-8/UTF-8,gbk/GBK....不指定就是IDE默认编码
  • 使用步骤:

    1. 创建OutPutStreamWrite对象,构造方法中传递字节输出流和指定的编码表名称
    2. 使用OutPutStreamWrite对象中的方法write,把字符转换为字节存储缓冲区(编码的一个过程)
    3. 使用OutPutStreamWrite对象中的flush,把内存缓冲区的字节刷新到文件中
    4. 释放资源
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("./javaBook/src/cn/edu/aku/unit10/Buffer/gbk.txt"),"GBK");
        osw.write("你好");
        osw.flush();
        osw.close();

InputStreamReader是字节通向字符流的桥梁

  • 构造方法

    • InputStreamReader(InputStream in)

    • InputStreamReader(InputStream in, String charsetName)

      • 参数

        • InputStream in:字节输入流,用来读取文件中保存的字节

        • String charsetName:指定字符集

  • 使用步骤:

    1. 创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称
    2. 使用InputStreamReader对象中的read读取文件
    3. 释放资源
  • 注意事项

    • 构造方法中指定的字符编码名要和文件的编码相同,否则会发生乱码
InputStreamReader isr = new InputStreamReader(new FileInputStream("./javaBook/src/cn/edu/aku/unit10/Buffer/gbk.txt"),"GBK");
        int len = 0;
        while ((len = isr.read())!=-1){
            System.out.println((char)len);
        }
        isr.close();
posted @ 2022-10-08 19:42  彼时听风  阅读(257)  评论(0)    收藏  举报