Java IO Learning Notes 8

Keywords: Java

Buffered Reader and Buffered Writer

  • These two classes are efficient to improve the speed of file reading. They provide a buffer for character input and output. They can significantly improve the speed of writing and reading. Especially for a large number of disk files, the following two classes are emphasized.

BufferedReader

  • Read the text from the character input stream and buffer each character, so as to achieve efficient reading of characters, arrays and rows. It should be noted that this city is for character stream rather than byte stream.
  • Typically, every read request made by Reader results in corresponding read requests for underlying characters or byte streams. Therefore, it is recommended that BufferedReader be used to wrap all Readers whose read() operations may be costly (such as FileReader and InputStreamReader)

Constructor

  • Buffered Reader (Reader in) creates a buffer character input stream using the default size input buffer.
  • Buffered Reader (Reader in, int sz) creates a buffer character input stream using a specified size input buffer.

Example

  • As you can see, the constructor uses Reader as an abstract class to initialize. As we said earlier, this is for character stream reading, so it can be initialized using FileReader,InputStreamReader, two subclasses of Reader class.
File file=new File("/tmp"+File.separator+"test"+File.separator+"test.txt");
BufferedReader bufferedReader=new BufferedReader(new FileReader(file));  //Instance with FileReader
//Use InputStreamReader to instantiate
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream(file)));

common method

  • close()
  • String readLine() Read a row of data
  • int read() Read a character, note that here is different from the byte, where the Chinese characters occupy a byte, as mentioned earlier when reading the byte stream. byte It takes three bytes to read Chinese characters
  • skip(int n) skip n Bytes
  • ready() Determine whether the stream is ready to be read.

Example

  • For console reading, as I said earlier, System.in returns an InputStream type, so you can instantiate it using InputStream Reader, which is a little redundant. We can use Scanner provided by java.util to input directly.
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
        String str=bufferedReader.readLine();  //Read the string entered by the console
        System.out.println(str);  //Print out
  • Used for reading files
 BufferedReader bufferedReader=new BufferedReader(new FileReader(file));
       // BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
//        bufferedReader.skip(2);//skip two bytes
//        
//        The first way to read
        while(bufferedReader.ready())     //Determine whether there are still characters
        {
            String str=bufferedReader.readLine();   //Read a line directly
            System.out.println(str);  
        }
        bufferedReader.close();
        
        //The second way of reading
        int len=bufferedReader.read();
        while(len!=-1)   //Determine whether to read the end of the file
        {
            System.out.print((char)len);  //Mandatory conversion to characters
            len=bufferedReader.read();
        }

        

BufferedWriter

  • Write text to the character output stream and buffer each character to provide efficient writing of individual characters, arrays and strings.
  • Usually Writer sends its output immediately to the underlying character or byte stream. Unless prompted output is required, it is recommended that Buffered Writer be used to wrap all Writers whose write() operations may be costly (such as FileWriters and Output Stream Writers). for example
PrintWriter out
   = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

Constructor

  • Buffered Writer (Writer out) creates a buffer character output stream using the default size output buffer.
  • Buffered Writer (Writer out, int sz) creates a new buffer character output stream using a given size output buffer.
File file=new File("/tmp"+File.separator+"test"+File.separator+"test.txt");
BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(file));

Note that FileWriter here is a subclass of Writer, so you can use it to instantiate

Common Functions

  • close()
  • flush()
  • newLine() Write a platform-related newline character
  • write(int data) Write a character, not an integer.
  • write(String str) Write a string
  • write(String str,int off,int len) Write a partial string
  • write(char[] c)
  • write(char[] c,int off,int len)

Example

        File file=new File("/tmp"+File.separator+"test"+File.separator+"test.txt");
        File file1=new File("/tmp"+File.separator+"test");
        File file2=new File("/tmp"+File.separator+"test"+File.separator+"demo.txt");
        if(!file1.exists())
        {
            file1.mkdir();
            System.out.println("Folder Creation Successful");
        }
        BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(file));
        String str="Chen Jiabing";
        int data=48;
        String name="chenjiabing";
        char[] chars=name.toCharArray();
        bufferedWriter.write(str);   //Write a string, and of course intercept a segment of the string.
        bufferedWriter.newLine();  //Write a newline character that comes with a platform, because each operating system has a different newline character
        bufferedWriter.write(data);   //It's not an integer that's written, it's the character that the integer represents.
        bufferedWriter.newLine();
        bufferedWriter.write(chars,1,4);  //Write character array
        bufferedWriter.flush();
        bufferedWriter.close()

Extension: Through the above learning, you don't feel a little tired of using this class to write file data, only to write String char type data, then we think of the Print Writer, which is a convenient class to write files, can specify any type of data in any format, the same is the output stream, we can combine them. A more powerful output stream is formed as follows:

        File file=new File("/tmp"+File.separator+"test"+File.separator+"test.txt");
        //Using BufferedWriter to instantiate PrintWriter can significantly improve the efficiency of writing.
        PrintWriter printWriter=new PrintWriter(new BufferedWriter(new FileWriter(file)));
        String name="Chen Jiabing";
        int age=22;
        float grade=99.9f;
        printWriter.printf("Full name:%s,Age:%s,grade:%s",name,age,grade);  //Formatted Writing
        printWriter.close();

Comprehensive examples

Transfer data from one file to another

package IO;

import java.io.*;

/**
 * Created by chenjiabing on 17-5-26.
 */
public class demo13 {

    /**
     * Common functions:
     * newLine()
     * write(String str)
     * write(String str,int off,int len)
     * write(Char[] c)
     * write(Char[] c,int off,int len)
     * write(int data)
     * close()
     * flush()
     */
    public static void main(String[] args) throws IOException {
        File file = new File("/tmp" + File.separator + "test" + File.separator + "test.txt");
        File file1 = new File("/tmp" + File.separator + "test");
        File file2 = new File("/tmp" + File.separator + "test" + File.separator + "demo.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file2));
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

        while (bufferedReader.ready()) {
            String str = bufferedReader.readLine();  //Read a row of data in the file test.txt
            bufferedWriter.write(str);   //Write this line of data to the file demo.txt
            bufferedWriter.newLine();
        }
        bufferedReader.close();
        bufferedWriter.flush();
        bufferedWriter.close();


    }
}

Reference Articles

Posted by mnewhart on Thu, 27 Jun 2019 14:34:39 -0700