바이트 단위로 읽는 스트림 중 최상위 스트림이다
InputStream은 추상 메서드를 포함한 추상 클래스이다
FileInputStream : 파일에서 바이트 단위로 자료를 읽는다
ByteArrayInputStream : byte 배열 메모리에서 바이트 단위로 자료를 읽는다
FilterInputStream : 기반 스트림에서 자료를 읽을 때 추각 기능을 제공하는 보조 스트림의 상위 클래스
int read() : 입력 스트림으로부터 한 바이트의 자료를 읽는다. 바이트 수 반환
int read(byte[] b) : 입력 스트림으로부터 b[]크기의 자료를 b[]에 읽습니다. 읽은 자료의 바이트 수 반환
int read(byte[] b, int off, int len) : b[]의 off변수 위치부터 저장하며 len만큼 읽는다. 읽은 자료의 바이트 수 반환
void close() : 입력 스트림과 연결된 대상 리소스를 닫는다
더이상 읽어드릴 자료가 없을 경우 정수 -1이 반환된다.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try(FileInputStream fis = new FileInputStream("/input.txt")){
int i;
while((i = fis.read()) != -1){
System.out.print((char)i);
}
System.out.print("end");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
자료를 read()로 한 바이트씩 읽는 것보다 배열을 사용하여 한꺼번에 읽는게 빠르다
이 메서드는 선언한 배열의 크기만큼 한꺼번에 자료를 읽는다.
그리고 읽어 들인 자료의 수를 반환한다.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try(FileInputStream fis = new FileInputStream("input.txt")){
byte[] bs = new byte[10];
int i;
while((i = fis.read(bs)) != -1){
for(byte b : bs){
System.out.print((char)b);
}
System.out.print(":" + i + "바이트 읽음");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
바이트 단위로 쓰는 스트림 중 최상위 스트림이다.
자료의 출력 대상에 따라 다른 스트림을 제공한다
FileOutputStream : 바이트 단위로 파일에 자료를 씁니다.
ByteArrayOutputStream : Byte 배열에 바이트 단위로 자료를 씁니다.
FilterOutputStream : 기반 스트림에서 자료를 쓸 때 추가 기능을 제공하는 보조 스트림의 상위 클래스
write(int b) : 한 바이트를 출력한다
write(byte[ ] b) : b[] 배열에 있는 자료를 출력한다
void write(byte[ ] b, int off, int len) : b[] 배열에 있는 자료의 off 부터 len 길이만큼 자료를 출력한다
void flush : 출력을 위해 잠시 자료가 머무르는 출력 버퍼를 강제로 비워 자료를 출력한다
close() : 출력 스트림과 연결된 대상 리소스를 닫는다. 출력 버퍼가 비워진다
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
try(FileOutputStream fos = new FileOutputStream("output.txt")){
fos.write(65);
fos.write(66);
fos.write(67);
} catch (Exception e) {
System.out.print("출력 실패");
throw new RuntimeException(e);
}
System.out.print("출력 완료");
}
}
output.txt를 보면 ABC가 적혀있다
FileOutputStream은 숫자를 해당 아스키 코드값의 문자로 변환하여 저장한다