IO字符流

  1. 字符流

java IO提供了两类流,按读写信息的内容分为

  • 字节流: InputStream,OutputStream. 读写的内容以字节为单位。
  • 字符流: Reader,Writer。 读写的内容以字符为单位。
  • 转换流:是一组高级流,能够将字节流转换成字符流。

输出字符转入文件

public class OWSDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        FileOutputStream fos = new FileOutputStream("osw.txt");

        OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
        String s = "not found anything";

        /*
        * osw写出字符的方法中
        * 会按照实例化对象时指定的字符集
        * 转换成字节再输出
        * */
        osw.write(s);
        osw.close();
    }
}

显示文件内内容

public class ISRDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        FileInputStream fis = new FileInputStream("osw.txt");

        InputStreamReader isr = new InputStreamReader(fis,"utf-8");

        int d;

        while ((d=isr.read())!=-1){
    
    
            System.out.print((char) d);
        }
        System.out.println("over");
        isr.close();

    }
}
  1. 缓冲字符流
    在这里插入图片描述
  • 缓冲字符流
    java.io.BufferedWriter
    java.io.BufferedReader
    使用缓冲对文件的内容进行块读写,提高读写效率

  • java.io.PrintWriter
    是BufferedWrite基础上的又一次加工
    具有自动刷新换行的功能

/*
* 缓冲字符流
* java.io.BufferedWriter
* java.io.BufferedReader
* 使用缓冲对文件的内容进行块读写,提高读写效率
*
* java.io.PrintWriter
* 是BufferedWrite基础上的又一次加工
* 具有自动刷新换行的功能
*
* */

public class PwDemo {
    
    
    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    
    
        PrintWriter pw = new PrintWriter("pwd.txt","utf-8");

        pw.println("像我这样优秀的人");
        pw.write("is a hero");
        System.out.println("over");

        pw.close();
    }
}

高级流由低级流转换,下面是转换过程

FileOutputStream fos = new FileOutputStream("pw.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw);

pw.println("解决");
pw.close();

おすすめ

転載: blog.csdn.net/sinat_33940108/article/details/120842635