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

바이트 기반 스트림 - 파일이나 배열의 내용을 읽어 들여 출력

경진 2008. 7. 13. 17:25
파일이나 배열의 내용을 읽어 들여 출력하는 클래스 작성 

파일이나 배열의 내용을 읽어 들여 출력하는 클래스를 작성한다. 프로그램을 실행할 때 인자로 'file'을 지정하면 이전에 작성했던 file.dat의 내용을 읽어 들여 화면에 출력하고, 인자를 array로 지정하면 알파벳 소문자가 저장되어 있는 배열의 내용을 읽어 들여 화면에 출력하는 프로그램이다.

import java.io.*;

public class FileArrayInputStreamTest {

    public static void print(InputStream in){
        byte[] buffer = new byte[512];
        int readcount = 0;
       
        try {
            while((readcount = in.read(buffer)) != -1){
                System.out.write(buffer, 0, readcount);
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    } // print
 
    public static void main(String[] args) {
        if(args.length != 1){
            System.out.println("사용법 : java FileArrayInputStreamTest file/array");
            System.exit(0);
        } // if end   
     
        if(args[0].equals("file")){   
            FileInputStream fis = null;
            try{
                fis = new FileInputStream("file.dat");
                // static 메소드 print()호출
                print(fis);
            }catch(Exception ex){
                System.out.println(ex);
            }finally{
                try {
                    fis.close();
                } catch (IOException e) {}
            }
        }else if(args[0].equals("array")){
            byte[] abc = new byte[26];
            for(int i = 0; i < 26; i++){
                abc[i] = (byte)('a' + i);
            }
            ByteArrayInputStream bais = null;
            try{
                bais = new ByteArrayInputStream(abc);
                // static 메소드 print()호출
                print(bais);
            }catch(Exception ex){
                System.out.println(ex);
            }finally{
                try {
                    bais.close();
                } catch (IOException e) {}
            }
        }else{
            System.out.println("사용법 : java FileArrayInputStreamTest file/array");
            System.exit(0);
        } // if
    } // main
}

    public static void print(InputStream in){
        byte[] buffer = new byte[512];
        int readcount = 0;
       
        try {
            while((readcount = in.read(buffer)) != -1){
                System.out.write(buffer, 0, readcount);
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    } // print

static한 print() 메소드는 InputStream을 인자로 받아들인다. 이는 InputStream의 자식 클래스나 자손 클래스의 객체를 모두 받아들일 수 있다.

즉, FileInputStream이나 ByteArrayInputStream 등의 객체에 대한 참조를 전달 받을 수 있다. 전달받은 후에는 InputStream에 있는 read() 메소드를 이용해서 읽어 들인 후, 표준 출력 장치로 출력하고 있다.

        if(args[0].equals("file")){   
            FileInputStream fis = null;
            try{
                fis = new FileInputStream("file.dat");
                // static 메소드 print()호출
                print(fis);
            }catch(Exception ex){
……
        }

file.dat로부터 읽어 들이는 FileInputStream을 생성한 후, print() 메소드의 인자로 전달한다. print 메소드는 InputStream 형식을 인자로 받아들이기 때문에 InputStream의 자식 클래스인 FileInpustStream을 인자로 전달받을 수 있으며, 파일 내용을 출력한다.

        }else if(args[0].equals("array")){
            byte[] abc = new byte[26];
            for(int i = 0; i < 26; i++){
                abc[i] = (byte)('a' + i);
            }
            ByteArrayInputStream bais = null;
            try{
                bais = new ByteArrayInputStream(abc);
                // static 메소드 print()호출
                print(bais);
            }catch(Exception ex){
……

abc 바이트 배열의 내용을 알파벳으로 초기화한 후, abc 바이트 배열로부터 읽어 들이는 ByteArrayInputStream을 생성한다. 생성한 ByteArrayInputStream 객체는 print() 메소드의 인자로 전달한다. rint 메소드는 InputStream 형식을 인자로 받아들이기 때문에 ByteArrayInputStream 형태의 객체도 인자로 받아들여 abc 바이트 배열의 내용을 출력하게 된다.

결과화면