티스토리 뷰

java.io.FileInputStream - 파일 내용 화면 출력

FileInputStream 는 InputStream 를 상속받았으며, 파일로 부터 바이트로 입력받아, 바이트 단위로 출력할 수 있는 클래스이다. FileInputStream 를 생성할 수 있는 방법으로는 다음 같이 존재한다.

FileInputStream 생성

// File 의 위치를 인수로
FileInputStream ex1 = new FileInputStream("");
// 실제 파일 Object를 인수로
FileInputStream ex2 = new FileInputStream(new File(""));

예제 1

package com.athlete.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class InputFilePrint {

	public static void main(String[] args) {	
		
		FileInputStream input = null;
		try{
			// 화면에 표시하고자 하는 파일을 선택한다.
			File file = new File("c:\\example\\File\\umejintan_new.txt");
			
			// FileInputStream 는 File object를 생성자 인수로 받을 수 있다. 			
			input = new FileInputStream(file);
			int i = 0;
			while((i = input.read()) != -1) {
				System.out.write(i);
			}
		} catch (IOException e) {
			System.out.println(e);
		} finally {
			try{
				// 생성된 InputStream Object를 닫아준다.
				input.close();
			} catch(IOException io) {}
		}
	}
}

결과


System.out.write() 를 이용하여 실제 파일의 내용을 확인 할 수 있다. 중요한 것은 IO 클래스를 생성한 후 에는 항상 close() 메소드를 호출하여 닫아 주어야 한다. finally 블록을 이용하여 닫아주도록 한다.FileInputStream 의 Read() 는 파일의 내용을 바이트 단위로 읽어 들린후 정수로 반환한다. 위의 예저는 파일의 내용을 1바이트씩 읽어 온다. 예제 2 의 경우엔 512 바이트씩 데이터를 읽어 출력한다. 속도를 생각한다면 다음 예제가 좋을 것이다.


package com.athlete.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class InputFilePrint {

	public static void main(String[] args) {	
		
		FileInputStream input = null;
		try{
			// 화면에 표시하고자 하는 파일을 선택한다.
			File file = new File("c:\\example\\File\\umejintan_new.txt");
			
			// FileInputStream 는 File object를 생성자 인수로 받을 수 있다. 			
			input = new FileInputStream(file);
			int readBuffer = 0;
			byte [] buffer = new byte[512];
			while((readBuffer = input.read(buffer)) != -1) {
				System.out.write(buffer, 0, readBuffer);
			}
		} catch (IOException e) {
			System.out.println(e);
		} finally {
			try{
				// 생성된 InputStream Object를 닫아준다.
				input.close();
			} catch(IOException io) {}
		}
	}
}


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함