當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。