理解io流产生和整体流程

字节流

父类抽象接口

  • outputstream 输入流
  • inputstream 输出流

子类实现方法(使用次数最多)

  • FileInputStream
  • FileOutputStream

可以从文件或者路径下读取

// 创建字节输出流对象
 方式一  已知文件下
 FileOutputStream(File file)
 File file = new File("fos.txt");
 FileOutputStream fos = new FileOutputStream(file);
 方式二  已知路劲下
 FileOutputStream(String name)  
 ```
#  转换流出现时机

为了读取字符 我们提供了转换流
InputStreamReader(InputStream is):用默认的编码读取数据
InputStreamReader(InputStream is,String charsetName):我们只定的编码读取数据
为什么说是转换流 我们可以看 构造参数(传入参数 是字节流 及:
InputStreamReader isr = new InputStreamReader(new FileInputStream(“oow.txt”), “UTF-8”);
同理:
OutputStreamWriter(OutputStream out):根据默认编码把字节流的数据转换为字符流
OutputStreamWriter(OutputStream out,StringcharsetName):根据指定编码把字节流数据转换为字符流把字节流转换为字符流。
字符流 = 字节流 +编码表
注意 一定要调用flush()

# 字符流出现时机

后来我们为了更加方便处理字符数据省略转换繁琐过程
出现:
FileReader fr = new FileReader(“c:\a.txt”);
FileWriter fw = new FileWriter(“d:\b.txt”);
直接读取字符 和写入字符
两者区别
InputStreamReader isr = new InputStreamReader(new FileInputStream(“oow.txt”), “UTF-8”);
这句话可以看出来转换流目的是可以指定字符集然而FileReader只能使用默认字符

# 高级流出现过程

这个时候我们又觉得这样一个字符字符读取速度还是有点慢 然而出现了高级流 字符缓冲流
BufferedReader
从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值就足够大了。
BufferedWriter:
public void newLine():根据系统来决定换行符
BufferedReader:
public String readLine():一次读取一行数据
包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
public class BufferedDemo {
public static void main(String[] args) throws IOException {
// write();
read();
}

private static void read() throws IOException {
    // 创建字符缓冲输入流对象
    BufferedReader br = new BufferedReader(new FileReader("bw2.txt"));

    // public String readLine():一次读取一行数据
    // String line = br.readLine();
    // System.out.println(line);
    // line = br.readLine();
    // System.out.println(line);

    // 最终版代码
    String line = null;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

    //释放资源
    br.close();
}

private static void write() throws IOException {
    // 创建字符缓冲输出流对象
    BufferedWriter bw = new BufferedWriter(new FileWriter("bw2.txt"));
    for (int x = 0; x < 10; x++) {
        bw.write("hello" + x);
        // bw.write("\r\n");
        bw.newLine();
        bw.flush();
    }
    bw.close();
}

}

复制文件 字符和字节都可以 复制图片和视频时候只能用字节

除了我们读取为了让windos 记事本能读懂 用字符流 之外 其余全部用字节流

public static void main(String[] args) throws IOException {
// 把文本文件中的数据存储到集合中
BufferedReader br = new BufferedReader(new FileReader(“b.txt”));
ArrayList array = new ArrayList();
String line = null;
while ((line = br.readLine()) != null) {
array.add(line);
}
br.close();

    // 随机产生一个索引
    Random r = new Random();
    int index = r.nextInt(array.size());

    // 根据该索引获取一个值
    String name = array.get(index);
    System.out.println("该幸运者是:" + name);
}
``` 

你可能感兴趣的:(java)