current position:Home>The use of flush () in Java

The use of flush () in Java

2022-01-26 23:16:00 Dawn_ Aorora

         about Java File operations in , Common are FileWriter() and FileReader(); Sometimes I don't pay attention to writing flush(), You will find errors in writing data or reading data , such as :

package lxt;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class q2 {
    public static void main(String[] args) {

        char[] arr=new char[19];
        String ss="daddda";
        File fl = new File("G:\\A.txt");
        try {


            if (fl.exists() == false) {

                fl.createNewFile();

            }
            FileWriter fw=new FileWriter(fl);
            fw.write(ss);
            fw.flush();
            FileReader Q=new FileReader(fl);
           int t= Q.read(arr);

            for (int i = 0; i < t; i++) {
                System.out.print(arr[i]);
            }

            //System.out.println(arr);

            fw.close();



        }catch (Exception e){

            System.out.println(" abnormal ");
        }
    }

}

         Will find , I'll pick it up as soon as I finish writing the document flush() Method , Read the data of the file and then flush()( Be careful close() The method includes flush Method ,close() Cannot read after closing stream , and flush() Flushing the buffer can also continue to operate on the file ), In this way, the normal writing, reading and writing of the file can be guaranteed , Summarize the above , If not add flush() Method , Will find , Can't write into the file , Can't read , At this time , All data stays in the buffer , and flush() Refresh means refresh , Empty buffer , Force the data in the buffer to be written to a file or read .

copyright notice
author[Dawn_ Aorora],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262315578833.html

Random recommended