FileInputStream 클래스

- 파일 시스템의 파일로 부터 파일 내용을 바이트 스트림으로 읽어 들이기 위해 사용된다.

- InputStream 클래스의 하위 클래스

- 파일이 존재하지 않으면 FileNotFoundException 예외가 발생

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Ex13_FileInputStream {

	public static void main(String[] args) {
		String pathname = "test2.txt";
		int data;
		FileInputStream fis = null;

		try {
			fis = new FileInputStream(pathname);
				// FileInputStream : 파일 입력 byte 스트림
				// 만약 파일이 존재하지 않으면 fileNotFoundException 발생
			
			// FileNotFoundException < IOException < Exception
			System.out.println(pathname+" 파일 내용...");
			
			while( (data = fis.read()) != -1) {
				// 파일에서 읽은 내용을 화면에 출력
				System.out.write(data);
			}
			System.out.flush();
		} catch (FileNotFoundException e) {
			// 파일이 존재하지 않는 경우
			// e.printStackTrace();
			System.out.println(pathname + "는/은 존재하지 않는 파일 입니다.");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fis != null) {
				try {
					fis.close();
				} catch (Exception e2) {
				}
			}
		}
	}

}

위와 같은 의미

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Ex14_FileInputStream {
	public static void main(String[] args) {
		String pathname = "text.txt";
		int data;
		
		try(FileInputStream fis = new FileInputStream(pathname)) {
			System.out.println(pathname + "파일 내용...");
			while ( (data = fis.read()) != -1) {
				System.out.write(data);
			}
			System.out.flush();
		} catch (FileNotFoundException e) {
			System.out.println(pathname+"은/는 존재하지 않는 파일 입니다.");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

FileInputStream(String name) 주어진 이름의 파일을 바이트 스트림으로 읽기 위한 FileInputStream 객체를 생성하는 메소드.

2021.08.24 - [쌍용강북교육센터/8월] - 0823_Java : FileOutStream 클래스 에서 저장한 파일을 읽어와 보았다.

+ Recent posts