2009년 5월 12일 화요일

FileReader.java - 파일의 내용을 한 줄씩 읽는다

자바 IO를 이용한 FileReader 예제 소스이다. 파일이 .txt 파일이면 정상적으로 파일의 내용을 한 줄씩 읽어들여 화면에 디스플레이해 준다(사실은 표준출력한다).

import java.io.*;

public class FileReader {
    public static void main (String[] args) {
        System.out.println ("Program to demonstrate reading from a file");
        
        BufferedReader br = null;
        String fileName = args[0];
        
        // If an error occurs, go to the "catch" block
        try {
            // FileInputStream fis = new FileInputStream (fileName);
            FileReader fis = new FileReader (fileName);
            br = new BufferedReader (fis);
        
            // continue to read lines while there are still some left to read
            while ( br.ready() ) {
                System.out.println (br.readLine());
            }
        
            // Close the input stream
            br.close();
        } catch (Exception e) {
            // Handle any error in opening the file
            System.err.println("File input error");
        }
    } // End of main method
    
} // End of the class FileReader

댓글 없음: