Java-IO(字节流和字符流的转换)

    在使用java的io流的时候,可能会出现把字节流转换成字符流或者把字节流转换成字符流,这个时候就需要对两种不同的流进行转换。

1.具体的类

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

 BufferedReader in
   = new BufferedReader(new InputStreamReader(System.in));

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

  Writer out
   = new BufferedWriter(new OutputStreamWriter(System.out));

2.使用

     1)从控制台输入,将输入的文本写入文件

     

package cn.yu.io;

import java.io.*;

public class Demo1 {
    /**
     * 从控制台输入后写入文件
     */
    public static void main(String[] args) {

        // 创建字节流对象 System.in 代表从控制台输入
        InputStream in = System.in;
        // 创建字符流对象
        BufferedWriter bw = null;
        BufferedReader br = null;

        try {
            // 实例化字符流对象 通过 InputStreamReader 将字节输入流转化成字符输入流
            br = new BufferedReader(new InputStreamReader(in));
            bw = new BufferedWriter(new FileWriter("a.txt"));
            // 定义读取数据的行
            String line = null;
            // 读取数据
            while ((line = br.readLine()) != null) {
                // 如果输入的是"exit"就退出
                if("exit".equals(line)){
                    break;
                }
                // 将数据写入文件
                bw.write(line);
                // 写入新的一行
                bw.newLine();
                // 刷新数据缓冲
                bw.flush();
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if(bw != null)
                    bw.close();
                if (br != null)
                    br.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

效果

Java-IO(字节流和字符流的转换)

    2)读取文件内容输出到控制台

package cn.yu.io;

import java.io.*;

public class Demo2 {

    /**
     * 读取文件输出到控制台
     */
    public static void main(String[] args) {

        // 定义字节输出流的对象
        OutputStream out = System.out;
        // 定义字节流的对象
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            // 实例化字节输出流 使用
            bw = new BufferedWriter(new OutputStreamWriter(out));
            br = new BufferedReader(new FileReader("a.txt"));
            // 定义读取行的字符串
            String line = null;
            // 读取数据
            while ((line = br.readLine()) != null) {
                // 输出到控制台
                bw.write(line);
                // 新的一行 
                bw.newLine();
                // 刷新缓冲
                bw.flush();
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if(bw != null)
                    bw.close();
                if (br != null)
                    br.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

效果

Java-IO(字节流和字符流的转换)

可能你已经发现,从控制台输入我完全可以用 Scanner,输出到控制台我完全可以用 System.out.println()

不是你太low,而是你没有看过 java的源代码,Scanner的底层用的是 InputStream

System.out.println() 就不用多说了