CHAPTER 01 | FIileOutputStream FileInputStream
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 멀팈캐스팅 소켓
FileOutputStream Class
메모리의 내용을 읽어서 파일로 저장하는 기능을 수행하는 클래스이다.
메모리 내용을 저장해야 할 파일을 지정해야 하는 부분이다. (새롭게 저장할 파일이나 기존의 파일을 지정해야 한다. )
*기존의 파일에 저장하면 OverWrite 가 되기 때문에 주의해야 한다.
static int size = 0;
static byte buffer[] = new byte[bufferSize];
public static void main(String args[]) throws IOException {
try{
FileOutputStream fout = new FileOutputStream("example.txt");
fout.write(buffer, 0, size);
} catch(IOException e) {
System.out.print(e + "읽을 수 없습니다.");
}
}
기존의 데이터가 지워지지 않고 기존 데이터에 이어서 저장하기 위해서는 무엇을 해야 할까?
: 자바는 열려진 모든 파일에 대해 FileDescriptor 객체를 생성한다. 실제 파일에 대한 참조자나 파일 내에서 읽기/쓰기 위치와 같은 정보들을 포함한다.
public final FileDescriptor getFD() throws IOException
static FileOutputStream fout;
public static void main(String args[]) {
try{
int bytesRead;
byte[] buffer = new byte[256];
fout = new FileOutputStream("example.txt");
while((bytesRead = System.in.read(buffer)) >= 0 )
fout.write(buffer, 0, bytesRead);
} catch(IOException e) {
System.out.print(e + "읽을 수 없습니다.");
} finally {
try{
if(fout != null) fout.close();
} catch(IOException e){}
}
}
키보드로부터 데이터를 읽어서 직접 파일로 저장하는 기능을 수행하는 클래스는 없다.
=> 그리하여 while 문 수행문에서 보는 것처럼 키보드로부터 데이터를 읽어서 메모리에 저장한 후에 메모리 내용을 파일에 저장하는 방식을 사용한다.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class WriteToFileEvent extends Frame implements ActionListener {
Label lfile, ldata;
TextField tfile, tdata;
Button save;
String filename, data;
byte[] buffer = new byte[80];
public WriteToFileEvent(String str) {
super(str);
setLayout(new FlowLayout());
lfile = new Label("파일이름을 입력하세요.");
add(lfile);
tfile = new TextField(20);
add(tfile);
ldata = new Label("데이터를 입력하세요.");
add(ldata);
tdata = new TextField(20);
add(tdata);
save = new Button("저장하기");
save.addActionListener(this);
add(save);
System.out.print("save :::" + save);
addWindowListener(new WinListener());
}
public static void main(String[] args) {
WriteToFileEvent text = new WriteToFileEvent("파일저장");
text.setSize(270, 180);
text.show();
}
@Override
public void actionPerformed(ActionEvent e) {
filename = tfile.getText();
data = tdata.getText();
System.out.print("data :::" + data);
buffer = data.getBytes();
System.out.print("buffer :::" + buffer);
try{ // 현재 루트(상대경로) 일 때
FileOutputStream fout = new FileOutputStream(filename);
// 절대경로일 때 : /Users/사용자이름/Documents/"
fout.write(buffer);
} catch (Exception ex){
System.out.println(ex.getMessage());
}
}
static class WinListener extends WindowAdapter {
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
}
FileInputStream Class
하드디스크와 같은 저장장치의 파일의 내용을 읽어서 메모리의 내용에 저장하는 기능을 수행하는 클래스이다.
* FileInputStream 클래스를 이용해서 example.txt 파일 내용을 읽어서 buffer 메모리에 저장하는 코드를 작성하려면?
FileInputStream fin = new FileInputStream("exeample.txt");
fin.read(buffer)
* FileInputStream 클래스를 이용해서 example_01.txt 파일 내용을 읽어서 buffer 메모리에 저장하는 코드를 작성하려면?
package Input;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFormFile {
public static void main(String[] args){
int bytesRead;
byte[] buffer = new byte[1024];
FileInputStream fin = null;
try{
fin = new FileInputStream("example_01.txt");
while((bytesRead = fin.read(buffer)) >= 0) {
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e){
System.out.println(e);
} finally {
try {if(fin != null) fin.close(); }
catch (IOException e){}
}
}
}
위와 같이 파일 데이터 읽기 -> 메모리 저장 -> 화면에 출력하는 순서이다.
파일을 읽어 직접 화면에 출력을 수행하는 클래스는 없다.
=> 그리하여 while 문 수행문에서 보는 것처럼 파일의 데이터를 읽어서 메모리에 저장한 후에 메모리 내용을 출력하는 방식을 사용한다.
package Input;
import java.awt.*;
import java.awt.event.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class ReadFromFileEvent extends Frame implements ActionListener {
Label lfile;
TextField tffile;
TextArea tadata;
String filename;
public ReadFromFileEvent(String str) {
super(str);
setLayout(new FlowLayout());
lfile = new Label("파일 이름을 입력하세요.");
add(lfile);
tffile = new TextField(20);
tffile.addActionListener(this);
add(tffile);
tadata = new TextArea(3, 35);
add(tadata);
addWindowListener(new WinListener());
}
public static void main(String[] args) {
ReadFromFileEvent text = new ReadFromFileEvent("파일읽기");
text.setSize(270, 160);
text.show();
}
@Override
public void actionPerformed(ActionEvent e) {
byte buffer[]= new byte[100];
filename = tffile.getText();
try{
FileInputStream fin = new FileInputStream(filename);
fin.read(buffer);
String data = new String(buffer);
tadata.setText(data);
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
class WinListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
살짝 복잡쓰하지만 이것들은 알아두는 것이 좋아보인다. (이걸 실행하면 어떤 결과가 나올 지는 예측할 수 있어야 한다. )
* db.txt 파일 내용을 db_copy.txt 파일로 복사하기 위해서는?
: db.txt 의 내용을 FileInputStream 클래스를 이용하여 bytes 로 Read해서 buffer 에 저장할 것이고 메모리에 저장하고 이 저장된 데이터를 db.copy 에 FileOutputStream 클래스를 이용하여 write 해야 한다.
package Input;
import java.io.*;
public class FileCopier {
public static void main(String[] args) throws IOException {
int bytesread;
byte[] buffer = new byte[1024];
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("db.txt");
fos = new FileOutputStream("db_copy.txt");
while ((bytesread = fis.read(buffer)) >= 0) {
fos.write(buffer, 0, bytesread);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
if (fis != null) fis.close();
if (fos != null) fos.close();
} catch (IOException e) { }
}
}
}
오늘은 FileOutputStream Class 와 FileINputStream Class 에 대해서 알아보았습니다.
다음은 Chapter 01 의 연습문제 4문제를 풀어보도록 하겠습니다 : )