Java字节流转换字符流

一、字节流转换字符流

有时需要将字节流转换为字符流,InputStreamReader和OutputStreamWriter是为实现这种转换而设计的。
InputStreamReader构造方法如下:

  • InputStreamReader(InputStream in):将字节流in转换为字符流对象,字符流使用默认字符集。
  • InputStreamReader(InputStream in, String charsetName):将字节流in转换为字符流对象, charsetName指定字符流的字符集,字符集主要有:US-ASCII、ISO-8859-1、UTF-8和UTF-16。 如果指定的字符集不支持会抛出UnsupportedEncodingException异常。

OutputStreamWriter构造方法如下:

  • OutputStreamWriter(OutputStream out):将字节流out转换为字符流对象,字符流使用默认字符集。
  • OutputStreamWriter(OutputStream out,String charsetName):将字节流out转换为字符流对象, charsetName指定字符流的字符集,如果指定的字符集不支持会抛出 UnsupportedEncodingException异常。

文件复制的案例改造成缓冲流实现,代码如下:

import java.io.*;

public class FileCopyWithBuffer {
    public static void main(String[] args) {
//        创建字节文件输入流对象
        try(FileInputStream fis = new FileInputStream("/Users/caizhengjie/Desktop/qq/123.txt");
//            创建转换流对象
            InputStreamReader isr = new InputStreamReader(fis);
//            创建字符缓冲流
            BufferedReader bis = new BufferedReader(isr);
//            创建字节文件输出流对象
            FileOutputStream fos = new FileOutputStream("/Users/caizhengjie/Desktop/qq/asd/1234.txt");
//            创建转换流对象
            OutputStreamWriter osw = new OutputStreamWriter(fos);
//            创建字符缓冲输出流对象
            BufferedWriter bos = new BufferedWriter(osw);
        ){
//            首先读取一行文本
            String line = bis.readLine();
            while (line!=null){
//                开始写入数据
                bos.write(line);
//                写一个换行符
                bos.newLine();
//                再读取一行文本
                line = bis.readLine();
            }
            System.out.println("复制完成");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述流从一个 文件字节流,构建转换流,再构建缓冲流,这个过程比较麻烦,在I/O流开发过程中经常遇到这种流 的“链条”。

以上内容仅供参考学习,如有侵权请联系我删除!
如果这篇文章对您有帮助,左下角的大拇指就是对博主最大的鼓励。
您的鼓励就是博主最大的动力!

发布了69 篇原创文章 · 获赞 7 · 访问量 3328

猜你喜欢

转载自blog.csdn.net/weixin_45366499/article/details/104316579