일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- 제어자
- Connection
- 다형성
- array
- 람다식
- 입출력
- 객체지향
- 인터페이스
- java
- File입출력
- 메서드
- for문
- 변수
- 상속
- Interface
- 커넥션 풀
- I/O
- StringBuffer
- JSP
- try-catch
- 배열
- 에러
- ToString
- 예외
- DB
- 내장 객체 영역
- StringBuffer클래스
- 예외처리
- 객체
- 접근제어자
Archives
- Today
- Total
ksouth9
입출력 I/O(3) - 바이트기반 보조스트림(2) 본문
DataInputStream과 DataOutputStream
- FilterInputStream/FilterOutputStream의 자손이다.
- DataInputStream은 DataInput인터페이스를, DataOutputStream은 DataOutput인터페이스를 각각 구현했다.
- 때문에, 데이터를 읽고 쓰는데 있어서 8가지 기본 자료형의 단위로 읽고 쓸 수 있다.
- 각 자료형의 크기가 다르므로, 출력한 데이터를 다시 읽어 올 때는 출력했을 때의 순서를 염두에 두어야 한다.
DataInputStream의 생성자와 메서드
메서드/생성자 | 설명 |
DataInputStream(InputStream in) | 주어진 InputStream 인스턴스를 기반스트림으로 하는 DataInputStream인스턴스를 생성한다. |
boolean readBoolean() byte readByte() char readChar() short readShort() int readInt() long readLong() float readFloat() double readDouble() int readUnsignedByte() int readUnsignedShort() |
각 타입에 맞게 값을 읽어 온다. 더 이상 읽을 값이 없으면 EOFException을 발생시킨다. |
void readFully(byte[]b) void readFully(byte[]b, int off, int len) |
입력스트림에서 지정된 배열의 크기만큼 또는 지정된 위치에서 len만큼데이터를 읽어온다. 파일의 끝에 도달하면 EOFExcpetion이 발생하고, I/O에러가 발생하면 IOException 이 발생한다. |
String readUTF() | UTF-8형식으로 쓰여진 문자를 읽는다. 더 이상 읽을 값이 없으면 EOFException이 발생한다. |
static String readUTF(DataInput in) | 입력스트림(in)에서 UTF-8형식의 유니코드를 읽어온다. |
int skipBytes(int n) | 현재 읽고 있는 위치에서 지정된 숫자(n) 만큼을 건너뛴다. |
DataOutputStream의 생성자와 메서드
메서드/생성자 | 설명 |
DataOutputStream(OutputStream out) | 주어진 OutputStream인스턴스를 기반스트림으로 하는 DataOutputStream인스턴스를 생성한다. |
void writeBoolean(boolean b) void writeByte(int b) void writeChar(int c) void writeChars(String s) void writeShort(int s) void writeInt(int i) void writeLong(long l) void writeFloat(float f) void writeDouble(double d) |
각 자료형에 알맞은 값들을 출력한다. |
void writeUTF(String s) | UTF형식으로 문자를 출력한다. |
void writeChars(String s) | 주어진 문자열을 출력한다. writeChar(int c)메서드를 여러번 호출한 결과와 같다. |
int size() | 지금까지 DataOutputStream에 쓰여진 byte의 수를 알려준다. |
sample.dat파일에 값들을 출력하는 예제
public class Test {
public static void main(String[] args) {
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream("sample.dat");
dos = new DataOutputStream(fos);
dos.writeInt(10);
dos.writeFloat(20.0f);
dos.writeBoolean(true);
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
sample.dat파일을 읽어서 화면에 출력하는 예제
public class test3 {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("sample.dat");
DataInputStream dis = new DataInputStream(fis);
System.out.println(dis.readInt());
System.out.println(dis.readFloat());
System.out.println(dis.readBoolean());
dis.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}//실행결과
10
20.0
true
문자로 데이터를 저장하면, 다시 데이터를 읽어 올 때 문자들을 실제 값으로 변환하는 과정을 거쳐야하고, 또 읽어야 할 데이터의 개수를 결정해야하는 번거로움이 있다. 하지만 이처럼 DataInputStream과 DataOutputStream을 사용하면, 데이터를 변환할 필요도 없고, 자리수를 세어서 따지지 않아도 되므로 편리하고 빠르게 데이터를 저장하고 읽을 수 있게 된다.
int형 배열 score의 값들을 DataOutputStream을 이용해서 score.dat파일에 출력하는 예제
public class Test {
public static void main(String[] args) {
int [] score = {100,90,95,85,50};
try {
FileOutputStream fos = new FileOutputStream("score.dat");
DataOutputStream dos = new DataOutputStream(fos);
for(int i=0; i<score.length;i++) {
dos.writeInt(score[i]);
}
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
score.dat 파일을 읽어서 데이터의 총합을 구하는 예제
public class Test3 {
public static void main(String[] args) {
int sum = 0;
int score = 0;
try (FileInputStream fis = new FileInputStream("score.dat");
DataInputStream dis = new DataInputStream(fis)){
while(true) {
score = dis.readInt();
System.out.println(score);
sum += score;
}
} catch(EOFException e) {
System.out.println("점수의 총합은 "+sum+" 입니다.");
} catch(IOException ie) {
ie.printStackTrace();
}
}
}//실행결과
100
90
95
85
50
점수의 총합은 420 입니다.
DataInputStream의 readInt()와 같이 데이터를 읽는 메서드는 더 이상 읽을 데이터가 없으면 EOFException을 발생시킨다. 그래서 다른 입력스트림들과는 달리 무한반복문과 EOFException을 처리하는 catch문을 이용해서 데이터를 읽는다.
try-with-resources문을 이용해서 close()를 직접 호출하지 않아도 자동호출되도록 할 수 있다.
'Java' 카테고리의 다른 글
입출력 I/O(3) - 바이트기반 보조스트림 (0) | 2022.04.21 |
---|---|
입출력 I/O(2) - 바이트기반 스트림 (0) | 2022.04.17 |
입출력 I/O(1) (0) | 2022.04.17 |
람다식(Lambda expression)(2) (0) | 2022.04.16 |
람다식(Lambda expression)(1) (0) | 2022.04.11 |