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

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

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

Java中BufferedWriter类的close()方法用于从缓冲区流中刷新字符,然后将其关闭。一旦流关闭,进一步调用 write() 和 append() 等方法将引发异常。

句法:

public void close()

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

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

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

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

方案一:

// Java program to illustrate
// BufferedWriter close() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
    {
        try {
  
            // 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);
  
            // Close the buffered writer
            buffWriter.close();
  
            System.out.println(
                stringWriter.getBuffer());
        }
        catch (Exception e) {
            System.out.println(
                "BufferedWriter is closed");
        }
    }
}
输出:
GEEKS

方案二:

// Java program to illustrate
// BufferedWriter close() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
    {
        try {
  
            // 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);
  
            // Close the buffered writer
            buffWriter.close();
  
            System.out.println(
                stringWriter.getBuffer());
  
            // It will throw exception
            buffWriter.write(
                "GEEKSFORGEEKS", 5, 8);
        }
        catch (Exception e) {
            System.out.println(
                "BufferedWriter is closed");
        }
    }
}
输出:
GEEKS
BufferedWriter is closed

参考: https: Java/io/BufferedWriter.html#close()