I/O flow study notes

I/O flow study notes

The essence of streaming is the transmission of data

  1. File class ①Create
    a File class
    File file = new File (file path); ②Get
    the name of the file file.getName(); ③Create a file file.createNewFile(); ④Judge whether the file exists file.exists(); ⑤ Create a folder file.mkdir() : Create a multi-level directory folder file.mkdirs();








  2. Byte stream FileInputStream and FileOutputStrem (read unit is byte)
    ① Read file FileInputStrem
    FileInputStream fileInputStream = new FileInputStream(file);
    int i = fileInputStream.read();
    while (i> 0){ System.out.println(( char)i); i = fileInputStream.read(); }


    // 以上读取文件的效率偏低
    FileInputStream fileInputStream = new FileInputStream(file);
    byte[] bytes = new byte[1024];  //1kb
    
    // 表示一次读取1kb
    int read = fileInputStream.read(bytes);
    // 对获得的数据进行数据转换
    String s = new String(bytes);
    ② 写入文本 FileOutputStrem
    FileOutputStream fileOutputStream = new FileOutputStream("F:/b.txt");
    fileOutputStream.write(写入的内容);
    
  3. Character stream Reader

    // Reader implementation class

     ① InputStremReader (传入的参数 是char)
     FileInputStream fileInputStream = new FileInputStream(file);
             //获取字符输入流 (需要传入一个字节流)
     InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"gbk");
     
             char[] c = new char[64];
             // 传入一个64位的char
             int read = inputStreamReader.read(c);
             System.out.println( new String(c));
             
     ② FileReader(相比上面,不需传入字节流和编码格式)
     FileReader fileReader = new FileReader(file);
      char[] c = new char[64];
             // 传入一个64位的char
             int read = inputStreamReader.read(c);
             System.out.println( new String(c));
             
     ③ BufferedReader(使用BufferedReader读取文本内容可以保证文本内容的格式不被打乱 ::缓冲流)
     
     		 FileInputStream fileInputStream = new FileInputStream(file);
             //获取字符输入流
             InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
    
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
             String line = null;
             while ((line=bufferedReader.readLine())!= null){
                 System.out.println(line);
             }
    

// Finally note: a stream needs to be closed after use, otherwise some operations cannot be completed

Guess you like

Origin blog.csdn.net/weixin_52065369/article/details/113974477