Java/18. IO 기반 입출력 및 네트워킹
Day 23 : 파일 입출력 - FileInputStream
pancakemaker
2021. 11. 18. 12:16
FileInputStream
: 파일로부터 바이트 단위로 읽어 들일 때 사용
: 그림, 오디오, 비디오, 텍스트 파일 등 모든 종류의 파일을 읽을 수 있음
객체 생성 방법
//방법 1
FileInpuStream fis = new FileInputStream("C:/Temp/image.gif");
//방법 2
File file = new File("C:/Temp/image.gif");
FileInputStream fis = new FileInputStream(file);
FileInputStream 객체가 생성될 때 파일과 직접 연결
만약 파일이 존재하지 않으면 FileNotFoundException 발생 → try-catch문으로 예외 처리
텍스트 파일을 읽고 출력
package sec04.exam02_fileinputstream_YJ;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class FileInputStreamExample {
public static void main(String[] args) {
try {
InputStream fis = new FileInputStream("C:/JavaProgramming/source/chap18/src/"
+ "sec04/exam02_fileinputstream_YJ/FileInputStreamExample.java");
int data;
while( (data = fis.read()) != -1) { //1byte씩 읽고 콘솔에 출력
System.out.write(data);
}
System.out.flush();
fis.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
package sec04.exam02_fileinputstream_YJ;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class FileInputStreamExample {
public static void main(String[] args) {
try {
InputStream fis = new FileInputStream("C:/JavaProgramming/source/chap18/src/"
+ "sec04/exam02_fileinputstream_YJ/FileInputStreamExample.java");
int data;
while( (data = fis.read()) != -1) { //1byte씩 읽고 콘솔에 출력
System.out.write(data);
}
System.out.flush();
fis.close();
} catch (Exception e) {
System.out.println(e);
}
}
}