Java中BufferedWriter類的close()方法用於從緩衝區流中清除字符,然後將其關閉。一旦關閉流,則進一步調用write()和append()之類的方法將引發異常。
用法:
public void close()
參數:此方法不接受任何參數。
返回值:此方法不返回任何值。
異常:如果發生I /O錯誤,則此方法將引發IOException。
以下示例程序旨在說明IO包中BufferedWriter類中的close()方法:
程序1:
// 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
程序2:
// 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://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close()
相關用法
- Java BufferedWriter flush()用法及代碼示例
- Java BufferedWriter write()用法及代碼示例
- Java BufferedWriter newLine()用法及代碼示例
- Java Formatter close()用法及代碼示例
- Java BufferedReader close()用法及代碼示例
- Java ByteArrayInputStream close()用法及代碼示例
- Java CharArrayReader close()用法及代碼示例
- Java ObjectInputStream close()用法及代碼示例
- Java Reader close()用法及代碼示例
- Java ByteArrayOutputSteam close()用法及代碼示例
- Java StringWriter close()用法及代碼示例
- Java Scanner close()用法及代碼示例
- Java BufferedInputStream close()用法及代碼示例
- Java Writer close()用法及代碼示例
- Java PrintStream close()用法及代碼示例
- Java CharArrayWriter close()用法及代碼示例
- Java PushbackReader close()用法及代碼示例
- Java PushbackInputStream close()用法及代碼示例
- Java PrintWriter close()用法及代碼示例
- Java StringReader close()用法及代碼示例
注:本文由純淨天空篩選整理自pp_pankaj大神的英文原創作品 BufferedWriter close() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。