ขณะที่คุณกำลังพยายามเขียนข้อมูลไปยังสตรีมโดยใช้วัตถุ BufferedWriter หลังจากเรียกใช้ write() เมธอด ข้อมูลจะถูกบัฟเฟอร์ในขั้นต้น ไม่มีอะไรจะถูกพิมพ์
ฟลัช() เมธอดใช้เพื่อผลักเนื้อหาของบัฟเฟอร์ไปยังสตรีมพื้นฐาน
ตัวอย่าง
ในโปรแกรม Java ต่อไปนี้ เรากำลังพยายามพิมพ์บรรทัดบนคอนโซล (Standard Output Stream) เราจะเรียกใช้เมธอด 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");
}
} แต่เนื่องจากคุณยังไม่ได้ล้างเนื้อหาใน Buffer of the BufferedWriter จึงไม่พิมพ์อะไรออกมา
ในการแก้ไขปัญหานี้ ให้เรียกใช้ flush() เมธอดหลังจากดำเนินการเขียน ()
ตัวอย่าง
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