📜  Java中的 BufferedWriter flush() 方法及示例

📅  最后修改于: 2022-05-13 01:55:30.956000             🧑  作者: Mango

Java中的 BufferedWriter flush() 方法及示例

Java中BufferedWriter类的flush()方法用于从缓冲的写入器流中刷新字符。

句法:

public void flush()
            throws IOException

指定者:该方法由Flushable接口的 flush() 方法指定。

覆盖:此方法覆盖Writer类的 flush() 方法。

参数:此方法不接受任何参数。

返回值:此方法不返回任何值。

异常:如果发生 I/O 错误,此方法将引发IOException

下面的程序说明了 IO 包中 BufferedWriter 类中的 flush() 方法:

方案一:

// Java program to illustrate
// BufferedWriter flush() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
  
        // Create the string Writer
        StringWriter stringWriter
            = new StringWriter();
  
        // Convert stringWriter to
        // bufferedWriter
        BufferedWriter buffWriter
            = new BufferedWriter(
                stringWriter);
  
        // Write "GEEKS" to buffer writer
        buffWriter.write(
            "GEEKSFORGEEKS", 0, 5);
  
        // Flush the buffer writer
        buffWriter.flush();
  
        System.out.println(
            stringWriter.getBuffer());
    }
}
输出:
GEEKS

方案二:

// Java program to illustrate
// BufferedWriter flush() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
        // Create the string Writer
        StringWriter stringWriter
            = new StringWriter();
  
        // Convert stringWriter to
        // bufferedWriter
        BufferedWriter buffWriter
            = new BufferedWriter(
                stringWriter);
  
        // Write "GEEKS" to buffered writer
        buffWriter.write(
            "GEEKSFORGEEKS", 0, 5);
  
        // Flush the buffered writer
        buffWriter.flush();
  
        System.out.println(
            stringWriter.getBuffer());
  
        // Write "GEEKSFORGEEKS"
        // to buffered writer
        buffWriter.write(
            "GEEKSFORGEEKS", 5, 8);
  
        // Flush the buffered writer
        buffWriter.flush();
  
        System.out.println(
            stringWriter.getBuffer());
    }
}
输出:
GEEKS
GEEKSFORGEEKS

参考:
https://docs.oracle.com/javase/10/docs/api/java Java()