Java中使用BufferedReader读取文件内容

1、首先创建FileReader对象
2、将FileReader传递给BufferedReader
3、采用BufferedReader的readLine()方法和read()方法来读取文件内容
4、最后一定要的finally语句中关闭BufferedReaders
5、FileReader与BufferedReader配合使用,File,FileInputStream,BufferedInputStream配合使用
 */

import java.io.*;

public class Exercise {
  
  public static void main(String args[]) {
    BufferedReader br = null;
    BufferedReader br2 = null;
    try {
      br = new BufferedReader(new FileReader("/home/zjz/Desktop/myfile.txt"));
      // The first way of reading the file
      System.out.println("Reading the file using readLine() method: ");
      String contentLine = br.readLine();
      while (contentLine != null) {
        System.out.println(contentLine);
        contentLine = br.readLine();
      }
      br2 = new BufferedReader(new FileReader("/home/zjz/Desktop/myfile2.txt"));
      // The second way of reading the file
      System.out.println("Reading the file using read() method: ");
      int num = 0;
      char ch;
      while ((num = br2.read()) != -1) {
        ch = (char) num;
        System.out.print(ch);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (br != null) {
          br.close();
        }
        if (br2 != null) {
          br2.close();
        }
      } catch (IOException e) {
        System.out.println("Error in closing the BufferedReader");
      }
    }
  }
}


From: http://beginnersbook.com/2014/01/how-to-read-file-in-java-bufferedinputstream/

你可能感兴趣的:(java,Java,BufferedReader,Java文件读取)