What is the use of in flush() and close() methods of BufferedWriter class in Java?
Java的BufferedWriter类用于将字符流写入指定的目的地(字符输出流)。它最初将所有字符存储在缓冲区中,并将缓冲区的内容推到目标位置,从而高效地写入字符,数组和字符串。
您可以在实例化此类时指定所需的缓冲区大小。
flush()方法
当您尝试使用BufferedWriter对象将数据写入Stream时,在调用write()方法之后,数据将首先被缓冲,但不会打印任何内容。
flush()方法用于将缓冲区的内容推送到基础Stream。
例
在下面的Java程序中,我们尝试在控制台上打印一行(标准输出流)。在这里,我们通过传递所需的String来调用write()方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 | import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; public class BufferedWriterExample { public static void main(String args[]) throws IOException { //Instantiating the OutputStreamWriter class OutputStreamWriter out = new OutputStreamWriter(System.out); //Instantiating the BufferedWriter BufferedWriter writer = new BufferedWriter(out); //Writing data to the console writer.write("Hello welcome to Tutorialspoint"); } } |
但是,由于尚未刷新BufferedWriter的Buffer的内容,因此不会打印任何内容。
若要解决此问题,请在执行write()之后调用flush()方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; public class BufferedWriterExample { public static void main(String args[]) throws IOException { //Instantiating the OutputStreamWriter class OutputStreamWriter out = new OutputStreamWriter(System.out); //Instantiating the BufferedWriter BufferedWriter writer = new BufferedWriter(out); //Writing data to the console writer.write("Hello welcome to Tutorialspoint"); writer.flush(); } } |
输出量
1 | Hello welcome to Tutorialspoint |