當您嘗試使用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中文網其他相關文章!