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


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


Java中BufferedReader类的close()方法用于关闭流并释放与流操作关联的所有系统资源。

用法:

public void close() 
            throws IOException

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

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

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



以下示例程序旨在说明IO包中BufferedReader类中的close()方法:

程序1:假设存在文件“c:/demo.txt”。

// Java program to illustrate 
// BufferedReader close() method 
  
import java.io.*; 
public class GFG { 
    public static void main(String[] args) 
        throws IOException 
    { 
  
        // Read stream file 'demo.txt' 
        // containing text "GEEKSFORGEEKS" 
        FileReader fileReader 
            = new FileReader( 
                "c:/demo.txt"); 
  
        // Convert fileReader to 
        // bufferedReader 
        BufferedReader buffReader 
            = new BufferedReader( 
                fileReader); 
  
        // Call read() method 
        while (buffReader.ready()) { 
            System.out.print( 
                (char)buffReader.read()); 
        } 
  
        // Call close() method 
        buffReader.close(); 
    } 
}
输入:
输出:

程序2:假设存在文件“c:/demo.txt”。

// Java program to illustrate 
// BufferedReader close() method 
  
import java.io.*; 
public class GFG { 
    public static void main(String[] args) 
        throws IOException 
    { 
        try { 
  
            // Read stream file 'demo.txt' 
            // containing text "GEEKSFORGEEKS" 
            FileReader fileReader 
                = new FileReader( 
                    "c:/demo.txt"); 
  
            // Convert fileReader to 
            // bufferedReader 
            BufferedReader buffReader 
                = new BufferedReader( 
                    fileReader); 
  
            // Call close() method 
            buffReader.close(); 
  
            // Call read() method 
            System.out.print( 
                (char)buffReader.read()); 
        } 
        catch (IOException e) { 
            // Exception is thrown 
            System.out.println( 
                "BufferedReader is closed"); 
        } 
    } 
}
输入:
输出:

参考:https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#close()




相关用法


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