当您尝试使用BufferedWriter对象向流中写入数据时,在调用write()方法后,数据将首先被缓冲,不会打印任何内容。
flush()方法用于将缓冲区的内容推送到底层流中。
在以下Java程序中,我们尝试在控制台(标准输出流)上打印一行。在这里,我们通过传递所需的字符串来调用write()方法。
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 缓冲区的内容,因此不会打印任何内容。
要解决此问题,请在执行后调用 flush() 方法write()。
实时演示
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(); } }
Hello welcome to Tutorialspoint
以上是BufferedWriter类中flush()方法的目的是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!