티스토리 뷰
CHAPTER 01 바이트 입출력 스트림
CHAPTER 02 필터 입출력 스트림
CHAPTER 03 파일처리 클래스
CHAPTER 04 문자 입출력 스트림
CHAPTER 05 인터넷 주소 처리
CHAPTER 06 URL 클래스를 이용하여 데이터 읽기
CHAPTER 07 TCP/IP 서버 소켓
CHAPTER 08 TCP/IP 클라이언트 소켓
CHAPTER 09 서버와 클라이언트 통신 프로그램
CHAPTER 10 채팅 프로그램 작성
CHAPTER 11 UDP 프로토콜
CHAPTER 12 URLConnection 클래스
CHAPTER 13 IP 멀티캐스팅 소켓
필터 입출력 스트림
바이트 단위가 아닌 한글이나 숫자와 같이 2바이트 이상의 데이터를 전송하거나 받기를 원할 때, 전송 속도를 높이기 위해 데이터를 버퍼에 저장하였다가 한 번에 전송하는 기능을 수행하는 클래스
기반 입출력 스트림 클래스
파일 및 네트워크에 바이트 단위로 데이터를 전송하는 기능을 수행하는 클래스 모음
필터 입출력 클래스
문자, 정수, 실수 등과 같은 데이터를 직접 전송할 수 있는 기능을 추가한 클래스 모음
필터 출력 클래스들의 상위 클래스는?
FilterOutputStream
필터 입력 클래스들의 상위 클래스는?
FilterInputStream
protected FilterOutputStream(OutputStream out)
protected FilterInputStream(InputStream in)
필터 클래스의 객체에 데이터를 전송하면 연결된 기반 스트림을 통하여 파일이나 다른 컴퓨터와 같은 목적지에 데이터가 전송된다.
FileInputStream FileOutputStream : 기반스트림, 한 번에 한 바이트씩만 데이터를 전송한다.
FileOutputStream fout = new FileOutputStream("example9.txt");
FilterOutputStream filterout = new FIlterOutputStream(fout);
filterout.write("안녕하세요");
구조가 어떻게 되냐면
파일 | FileInputStream / FileOutputStream | FilterInputStream / FilterOutputStream | 프로그램 |
Byte | int, float, char |
자바에서는 정수가 4바이트로 구성되기 때문에 기반 스트림 클래스를 사용하면 정수를 전송하기 위해서 프로그램으로 4번의 write() 메소드를 실행시켜야 한다. 기반 스트림에 연결하여 정수, 문자 및 실수와 같이 자료형 별로 데이터를 전송하는 기능을 구현하는 클래스가 DataOutputStream 및 DataInputStream 클래스이다.
DataOutputStream
: 바이트 단위뿐 아니라 부울 값, 정수, 실수, 문자, 문자열과 같은 자료형 데이터를 전송하는 메소드도 포함한다.
정수 27777을 쓰기 위해서는 아래와 같이 작성해야 한다.
package Output;
import java.io.*;
public class DataStream {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("db.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.write(27777);
}
}
단, 아래와 같이 자료형을 정확히 써줘야 한다.
dos.writeInt(27777);
dos.writeBoolean(true);
dos.writeChars("안녕");
하지만 실행한 결과 db.txt 파일에는 이상한 값이 저장된다 . . . 문자가 아닌 2진 숫자로 저장이 되기 때문이다.
l��H�U
UTF 로 쓰니 잘 되더라ㅣ ㅋㅋ
dos.writeUTF("안녕");
DataInputStream
: 바이트 단위뿐 아니라 부울 값, 정수, 실수, 문자, 문자열과 같은 자료형 데이터를 수신하는 메소드도 포함한다.
//파일 읽기
FileInputStream fis = new FileInputStream("db.txt");
DataInputStream dis = new DataInputStream(fis);
int dataInt = dis.readInt();
int dataStr = dis.readChar();
System.out.println(dataInt);
System.out.println(dataStr);
몇 바이트인지 확인하기 위해서는 ?
System.out.print(dos.size());
고객의 계좌번호를 입력받아서 client.txt 에 저장하는 GUI 를 구현하려면 ?
package Output;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateSeqFile extends Frame implements ActionListener {
private TextField account, name, balance;
private Button enter, done;
private FileOutputStream file;
private DataOutputStream output;
public CreateSeqFile() {
super("고객 파일을 생성한다. ");
try {
file = new FileOutputStream("client.txt");
output = new DataOutputStream(file);
} catch (Exception e) {
System.out.println(e.toString());
System.exit(1);
}
setSize(250, 130);
setLayout( new GridLayout(4,2));
add( new Label("계좌번호 "));
account = new TextField(10);
add(account);
add( new Label("이름 "));
name = new TextField(10);
add(name);
add( new Label("잔고 "));
balance = new TextField(10);
add(balance);
enter = new Button("입력");
enter.addActionListener(this);
add(enter);
done = new Button("닫기");
done.addActionListener(this);
add(done);
setVisible(true);
}
public void addRecord() throws IOException {
int accountNo = 0;
String d;
if(!account.getText().isEmpty()){
try {
String reAccount =account.getText().replace("-", "");
accountNo = Integer.parseInt(reAccount);
if (accountNo > 0) {
output.writeInt(accountNo);
output.writeUTF(name.getText());
d = balance.getText();
output.writeDouble(Double.valueOf(d));
account.setText("");
name.setText("");
balance.setText("");
}
} catch (NumberFormatException nfe) {
System.err.print("정수를 입력해야 합니다. ");
} catch (IOException ioe) {
System.err.print(ioe.toString());
System.exit(1);
}
}
}
@Override
public void actionPerformed(ActionEvent e) { //이벤트 리스너
try {
addRecord();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
if(e.getSource() == done){
try{
output.close();
} catch (IOException ioe) {
System.err.println(ioe.toString());
}
System.exit(0);
}
}
public static void main (String args[]) {
new CreateSeqFile();
}
}
client.txt 파일의 내용을 읽어 GUI 에 표시하려면 ?
package Output;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class ReadSeqFile extends Frame implements ActionListener {
private TextField account, name, balance;
private Button enter, done;
private FileInputStream file;
private DataInputStream input;
public ReadSeqFile() {
super("고객 파일을 읽는다. ");
try {
file = new FileInputStream("client.txt");
input = new DataInputStream(file);
} catch (Exception e) {
System.out.println(e.toString());
System.exit(1);
}
setSize(250, 130);
setLayout( new GridLayout(4,2));
add( new Label("계좌번호 "));
account = new TextField();
account.setEditable(false);
add(account);
add( new Label("이름 "));
name = new TextField();
name.setEditable(false);
add(name);
add( new Label("잔고 "));
balance = new TextField();
balance.setEditable(false);
add(balance);
enter = new Button("출력");
enter.addActionListener(this);
add(enter);
done = new Button("닫기");
done.addActionListener(this);
add(done);
setVisible(true);
}
public void readRecord() throws IOException {
int accountNo ;
String Rname;
double Rbalance;
try {
System.out.print("\n값 : " + input);
accountNo = input.readInt();
Rname = input.readUTF();
Rbalance = input.readDouble();
account.setText(String.valueOf(accountNo));
name.setText(Rname);
balance.setText(String.valueOf(Rbalance));
} catch (EOFException Eof) {
System.err.print(Eof.toString());
System.exit(1);
}
}
@Override
public void actionPerformed(ActionEvent e) { //이벤트 리스너
if(e.getSource() == enter){
try {
readRecord();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if(e.getSource() == done){
try{
input.close();
} catch (IOException ioe) {
System.err.println(ioe.toString());
}
System.exit(0);
}
}
public static void main (String args[]) {
new ReadSeqFile();
}
}
다음은 많이 사용하는 BufferedInputStream 과 BufferedOutputStream 클래스와 PrintStream 클래스에 대해서 알아보겠습니당.
'자바 | JAVA > JAVA | 채팅 프로그래밍' 카테고리의 다른 글
CHAPTER 02 | BufferedInputStream BufferedInputStream (2) | 2025.06.25 |
---|---|
CHAPTER 01 | 연습문제 3 ~ 4번 (2) | 2025.06.24 |
CHAPTER 01 | 연습문제 2번 (0) | 2025.06.24 |
CHAPTER 01 | 연습문제 1번 (0) | 2025.06.18 |
CHAPTER 01 | 연습문제 (1) | 2025.06.18 |