Java 파일 읽기 (Read)

파일을 생성하고 디렉토리를 생성하는 방법을 배웠다.

파일이 생성되었기 때문에 이제 파일에 접근해서 읽고, 파일에 무엇이 저장되어 있는지 확인할 수 있다.

모든 파일은 텍스트로 이루어져있다고 생각하면 된다. 심지어 이미지 파일도 문자로 이루어져 있기 때문에 파일을 읽을 때 문자를 읽는 다고 생각하면 된다.

그리고 자바에 파일을 읽는 방법은 한글자씩 읽는 방법과 파일을 한줄씩 읽는 방법이 있는데, 두가지 방법에 대해 학습해본다.

  • 파일 읽기
    • FileReder 를 통한 파일 읽기
    • BufferedReader 를 통한 파일 읽기

파일 읽기

파일을 읽을 때는 기본적으로 java.io.FileReader 가 사용된다. 생성된 파일을 객체로 선언하고, 선언된 파일 객체를 인자로 FileReader 를 선언하면 파일에 직접 접근하여 파일을 읽을 수 있다.


hello.txt

Hello world
This is file reader.


파일 읽기( FileReder )

class readFile{
  public static void main(String[] args){
    File file = new File("/Users/kyungseok_park/Desktop/hello.txt");
    try{
      if(checkBeforeFile(file)){
        //file을 인자로 FileReader객체를 선언했다.
        //이 객체를 통해 파일을 읽을 수 있다.
        FileReader fr = new FileReader(file);

        //FileReader 객체를 통해 파일을 한글자씩 읽어 ch변수에 할당한다.
        //.read() 메소드의 리턴이 int형이기 때문에 ch를 int로 선언해주어야 한다.
        int ch = fr.read();

        while(ch != -1){	//-1을 EOP 라고 부르며 파일의 끝을 나타낸다. (End Of File)
          //한글자씩 출력
          System.out.println((char)ch);
          //다음 글자를 읽는다.
          ch = fr.read();
        }

      }else{
        System.out.println("파일에 접근할 수 없습니다.");
      }
    } catch (FileNotFoundException ex){
      //파일을 찾을 수 없을때
      ex.printStackTrace();
    } catch (IOException e) {
      //파일 읽기 중 에러가 발생했을 때
      e.printStackTrace();
    }
  }

  static boolean checkBeforeFile(File file){
    //파일이 존재하고
    if(file.exists()){
      //그 파일이 파일이고, 읽을 수 있다면 true를 리턴한다.
      if(file.isFile() && file.canRead()){
        return true;
      }
    }
    return false;
  }
}
H
e
l
l
o

w
o
r
l
d


T
h
i
s

i
s

f
i
l
e

r
e
a
d
e
r
.

출력 결과에서 확인할 수 있듯이 FileReader 는 파일을 한글자씩 읽어올 수 있다.

지금 읽은 hello.txt 파일은 짧은 글의 파일이라 한글자씩 읽어도 성능에는 큰 무리가 없었다. 하지만, 파일이 10,000줄 이상을 넘어가도 한글자씩 읽는 것이 효과적일까?

그래서 등장한 것이 FileReader 의 확장판 같은 개념인 BufferedReader 이다.



파일 읽기( BufferedReader )

class bufferdReader{
  public static void main(String[] args) {
    File file = new File("/Users/kyungseok_park/Desktop/hello.txt");
    try{
      if(checkBeforeFile(file)){
        //FileReader를 인자로 하는 BufferedReader 객체 생성
        BufferedReader br = new BufferedReader(new FileReader(file));

        //파일을 한 문장씩 읽어온다.
        String str = br.readLine();

        //EOF는 null문자를 포함하고 있다.
        while(str != null){
          //읽은 문자열을 출력한다.
          System.out.println(str);
          //다음 문자열을 가르켜준다.
          str = br.readLine();
        }
		//FileReader와는 다르게 사용 후 꼭 닫아주어야 한다.
        br.close();
      }else{
        System.out.println("파일에 접근할 수 없습니다.");
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  static boolean checkBeforeFile(File file){
    if(file.exists()){
      if(file.isFile() && file.canRead()){
        return true;
      }
    }
    return false;
  }
}
Hello world
This is file reader.

파일을 한 문장씩 읽기 때문에 FileReader 보다는 훨씬 빠르다. 파일을 읽는 코드의 대부분은 BufferedReader 로 만들어져 있다.

Comments