InputStream
- 바이트 단위 입력 스트림의 최상위 추상 클래스
- 많은 추상 메서드가 선언되어 있고, 이를 하위 스트림에서 상속받아 구현
- 주요 하위 클래스
스트림 클래스 | 설명 |
FileInputStream | 파일에서 바이트 단위로 자료를 읽음 |
ByteArrayInputStream | byte 배열 메모리에서 바이트 단위로 자료를 읽음 |
FilterInputStream | 보조 스트림의 최상위 클래스 |
- 주요 메서드
메서드 | 설명 |
int read() | 입력 스트림으로부터 한 바이트의 자료를 읽음. 읽은 자료의 바이트 수 반환 |
int read(byte[] b) | 입력 스트림으로부터 b[] 크기의 자료를 b[]에 읽음. 읽은 자료의 바이트 수 반환 |
int read(byte b[], int off, int len) | 입력 스트림으로부터 b[] 크기의 자료를 b[]의 off 변수 위치부터 저장하며 len만큼 읽음. 읽은 자료의 바이트 수 반환 |
void close() | 입력 스트림과 연결된 대상 리소스를 닫음 |
예제 코드
FileInputStreamTest1.java
- 파일을 한바이트씩 읽어들임
package ch14;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamTest1 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("input.txt"); // FileInputStream 생성
System.out.println((char)fis.read()); // Byte 단위로 읽음
System.out.println((char)fis.read());
System.out.println((char)fis.read());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
} finally {
try {
fis.close(); // 파일 close
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("end");
}
}
수행 결과
- input.txt 파일이 없을 경우
- input.txt 파일이 있을 경우 (ABC)
A
B
C
end
FileInputStreamTest2.java
- 파일의 끝까지 한바이트씩 읽어들임
- read() 메서드는 자료의 바이트 수를 반환하고 자료의 마지막일 경우 -1 반환
package ch14;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest2 {
public static void main(String[] args) {
try(FileInputStream fis = new FileInputStream("input.txt")) { // autoclose됨
int i;
while((i = fis.read()) != -1) { // 파일의 끝일 경우 -1 반환
System.out.print((char)i);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
수행 결과
ABC
FileInputStreamTest3.java
- 바이트 배열을 이용해서 파일 읽어들임
package ch14;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamTest3 {
public static void main(String[] args) {
int i;
try(FileInputStream fis = new FileInputStream("input2.txt")) {
byte[] bs = new byte[10]; // 바이트 배열 생성
while((i = fis.read(bs)) != -1) { // -1일 경우 end of file
for(int j = 0 ; j < bs.length ; j++) { // 배열의 길이만큼 읽음
System.out.print((char)bs[j]);
}
System.out.println(" : " + i + "바이트 읽음");
}
} catch (IOException e){
System.out.println(e);
}
}
}
수행 결과
- 버퍼에 이전에 사용했던 값이 남아있음
ABCDEFGHIJ : 10바이트 읽음
KLMNOPQRST : 10바이트 읽음
UVWXYZQRST : 6바이트 읽음 // 6바이트 이후 기존에 저장된 버퍼 값 출력
for문의 조건문 수정
while((i = fis.read(bs)) != -1) { // 바이트 수, -1일 경우 end of file
for(int j = 0 ; j < i ; j++) { // 바이트 수만큼 읽음
System.out.print((char)bs[j]);
}
System.out.println(" : " + i + "바이트 읽음");
}
수행 결과
ABCDEFGHIJ : 10바이트 읽음
KLMNOPQRST : 10바이트 읽음
UVWXYZ : 6바이트 읽음
OutputStream
- 바이트 단위 출력 스트림의 최상위 추상 클래스
- 많은 추상 메서드가 선언되어 있고, 이를 하위 스트림에서 상속받아 구현
- 주요 하위 클래스
스트림 클래스 설명 FileOutputStream 파일에서 바이트 단위로 자료를 씀 ByteArrayOutputStream byte 배열 메모리에서 바이트 단위로 자료를 씀 FilterOutputStream 보조 스트림의 최상위 클래스
- 주요 메서드
메서드 설명 int write() 한 바이트 출력 int write(byte[] b) b[] 크기의 자료를 출력 int write(byte b[], int off, int len) b[] 배열에 있는 자료의 off 위치부터 len 개수만큼 자료 출력 void flush() 출력을 위해 자료가 머무르는 출력 버퍼를 강제로 비워 자료를 출력. 소켓 혹은 네트워크에서 가끔 사용 void close() 출력 스트림과 연결된 대상 리소스를 닫음. 출력 버퍼 비워짐 (flush() 호출됨)
예제 코드
FileOutputStreamTest1.java
- 파일에 한바이트 씩 출력
- 입력 스트림은 스트림에 파일이 없을 때 FileNotFoundException이 떨어지지만 출력 스트림은 파일을 생성함
package ch14;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamTest1 {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("output.txt");) { // 출력 스트림 생성
// 한 바이트씩 write
fos.write(65); // A
fos.write(66); // B
fos.write(67); // C
} catch (IOException e) {
System.out.println(e);
}
System.out.println("end");
}
}
FileOutputStreamTest2.java
- 바이트 배열 출력
package ch14;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamTest2 {
public static void main(String[] args) throws FileNotFoundException {
FileOutputStream fos = new FileOutputStream("output2.txt"); // 출력 스트림 생성
try(fos) { // try의 변수로 스트림 인스턴스 입력, autoclose됨
byte[] bs = new byte[26];
byte data = 65;
for(int i = 0; i < bs.length; i++) {
bs[i] = data++;
}
fos.write(bs); // A~Z
} catch(IOException e) {
System.out.println(e);
}
System.out.println("end");
}
}
'Java & Kotlin' 카테고리의 다른 글
[Java 기능] 문자 단위 입출력 스트림 (0) | 2022.02.17 |
---|---|
[Java 기능] 표준 입출력 스트림 (0) | 2022.02.16 |
[Java 기능] I/O 스트림 (0) | 2022.02.16 |