Java BufferedWriter.close()方法範例
BufferedWriter
的Java BufferedWriter.close()
方法的語法如下。
public void close() throws IOException
在下面的程式碼中展示了如何使用BufferedWriter.close()
方法。
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
public class Main {
public static void main(String[] args) throws IOException {
StringWriter sw = new StringWriter(); // From: Ww w .y iI B AI .c OM
BufferedWriter bw = new BufferedWriter(sw);
bw.append("tw511.com");
bw.close();
System.out.println(sw.getBuffer());
// appending after closing will throw error
bw.append("2");
System.out.println(sw.getBuffer());
}
}
上面的程式碼生成以下結果。
Exception in thread "main" tw511.com
java.io.IOException: Stream closed
at java.io.BufferedWriter.ensureOpen(BufferedWriter.java:116)
at java.io.BufferedWriter.write(BufferedWriter.java:221)
at java.io.Writer.write(Writer.java:157)
at java.io.Writer.append(Writer.java:227)
at Main.main(Main.java:19)