// 보조 스트림 기본 구조
MainStream mainStream = new MainStream();
SecondaryStream secondaryStream = new SecondaryStream(mainStream);
public class DataOutputStreamExample {
public void writeData() throws IOException {
try (DataOutputStream dos = new DataOutputStream(
new FileOutputStream("data.bin"))) {
// 기본 데이터 타입 쓰기
dos.writeInt(100); // 정수 쓰기
dos.writeDouble(3.14); // 실수 쓰기
dos.writeBoolean(true); // 논리값 쓰기
dos.writeUTF("Hello"); // UTF-8 문자열 쓰기
}
}
}
public class DataInputStreamExample {
public void readData() throws IOException {
try (DataInputStream dis = new DataInputStream(
new FileInputStream("data.bin"))) {
// 기본 데이터 타입 읽기
int number = dis.readInt(); // 정수 읽기
double value = dis.readDouble(); // 실수 읽기
boolean flag = dis.readBoolean(); // 논리값 읽기
String text = dis.readUTF(); // UTF-8 문자열 읽기
}
}
}
기본 데이터 타입의 효율적 처리
네트워크 통신
// 쓰기 순서
dos.writeInt(100);
dos.writeDouble(3.14);
dos.writeUTF("Hello");
// 읽기 순서 (반드시 쓰기 순서와 동일해야 함)
int num = dis.readInt();
double val = dis.readDouble();
String str = dis.readUTF();
바이너리 데이터 특성
플랫폼 독립성
public class DataStreamExample {
public void saveData(Person person) throws IOException {
try (DataOutputStream dos = new DataOutputStream(
new FileOutputStream("person.dat"))) {
dos.writeUTF(person.getName());
dos.writeInt(person.getAge());
dos.writeDouble(person.getSalary());
}
}
public Person loadData() throws IOException {
try (DataInputStream dis = new DataInputStream(
new FileInputStream("person.dat"))) {
String name = dis.readUTF();
int age = dis.readInt();
double salary = dis.readDouble();
return new Person(name, age, salary);
}
}
}