개인참고자료/자바(네트워크)

바이트 기반 스트림 - 파일의 내용을 읽어 들여 화면에 출력

경진 2008. 7. 13. 16:50
파일의 내용을 읽어 들여 화면에 출력하는 프로그램 

import java.io.*;

public class FileView {

    public static void main(String[] args) {
        if(args.length != 1){
            System.out.println("사용법 : java FileView 파일이름");
            System.exit(0);
        } // if end

        FileInputStream fis = null;
        try{
            fis = new FileInputStream(args[0]);
            int i = 0;
            while((i = fis.read()) != -1){
                System.out.write(i);
            }
        }catch(Exception ex){
            System.out.println(ex);
        }finally{
            try {
                fis.close();
            } catch (IOException e) {}
        }
    } // main
}

        FileInputStream fis = null;
        try{
            fis = new FileInputStream(args[0]); // IO 클래스를 try 문 안에 선언, 생성 한다.
………
            }
        }catch(Exception ex){
            System.out.println(ex);
        }finally{
            try {
                fis.close(); // 사용한 자원은 반드시 반납한다.
            } catch (IOException e) {}
        }

System.in, System.out, System.err의 세 가지 스트림을 제외하고 앞으로 IO 클래스를 사용할 때는 반드시 다음 내용을 지켜야 한다.

try문에서 사용할 IO 클래스를 선언한다. 보통 null값을 할당한다.
try 블록 안에서 IO 클래스 객체를 생성한다.
finally 블록 안에서 IO 클래스의 close() 메소드를 호출한다.

IO 클래스를 사용한 후에는 반드시 close() 메소드를 사용함으로써 사용했던 자원을 반납해야한다.

            fis = new FileInputStream(args[0]);
            int i = 0;
            while((i = fis.read()) != -1){
                System.out.write(i);
            }

FileInputStream의 read() 메소드는 파일의 시작부터 차례대로 바이트 단위로 읽어 들인다. 읽어들인 값은 정수 하위 8비트에 저장해서 반환되고, 반환받은 값은 System.out에 있는 wirte() 메소드를 이용해서 화면에 출력한다.

Command 창 결과 화면

결과화면

이클립스(eclipse)를 이용한 결과 화면

그림1

그림2

그림3