当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java BufferedWriter close()用法及代码示例


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()




相关用法


注:本文由纯净天空筛选整理自pp_pankaj大神的英文原创作品 BufferedWriter close() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。