JAVA
자바 IO - Stream ( Ⅰ )
choi121xx
2014. 9. 12. 15:04
1. 자바의 IO
- 데이터를 읽어 오거나 출력에 관련된 작업
- 스트림: 자바는 데이터를 입출력할때 스트림(Stream)을 사용한다. 스트림은 데이터의 흐름이다.
- 스트림은 근원지(Source)와 목적지(Destination)가 존재한다.(단방향, 한방향으로 이동)
- 스트림의 종류
1) 바이트단위로 구분
- 1바이트 스트림 : 1바이트 단위로 처리, ~InputStream, ~OutputStream
- 2바이트 스트림 : 2바이트 단위로 처리(문자처리 때문에 만들어짐)
~Reader, ~Writer
2) 입출력으로 구분
- 입력 스트림 : 읽어오는 기능 ~InputStream, ~Reader
- 출력 스트림 : 출력하는 기능 ~OutputStream,~Writer
3) 기능으로 구분
- NodeStream : 가장 기본적인 스트림 InputStream, OutputStream
- BridgeStream : 1바이트스트림을 2바이트스트림으로 변환
- FilterStream : NodeStream에 여러 편리한 기능을 덧붙인 스트림
ex> InputStream
import java.io.InputStream;
import java.io.IOException;
public class Test01_NodeStream
{
public static void main(String[] args)
{
//키보드와 연결된 입력 스트림객체 얻어오기
InputStream in=System.in;
try{
System.out.println("글자 딱 하나만 입력하세요!");
//public abstract int read() throws IOException
//키보드로 읽어온 데이터를 바이트단위로 얻어오기
int n=in.read();
System.out.println("입력된글자:" + (char)n);
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}
ex> InputStreamReader
package test01.node;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class Test02_Reader
{
public static void main(String[] args)
{
//InputStreamReader(InputStream in)
InputStream in=System.in;
Reader rd=new InputStreamReader(in);
System.out.println("딱 하나의 문자만 입력");
try
{
//public int read() throws IOException
int n=rd.read();
System.out.println("입력된 글자:" +(char)n);
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}
ex> 표준출력장치 (모니터--> System.out)과 연결된 출력객체 얻어오기
package test01.node;
import java.io.IOException;
import java.io.OutputStream;
public class Test03_OutputStream
{
public static void main(String[] args)
{
//표준출력장치(모니터==>System.out)과 연결된 출력객체 얻어오기
OutputStream out=System.out;
int a=65;
try{
out.write(a);
//버퍼가 다차지 않아도 강제로 데이터를 내보내라(출력해라!)
//out.flush();
//void write(byte[] b)
byte []b={65,66,67,68};
out.write(b);
}catch(IOException ie){
System.out.println(ie.getMessage());
}finally{
try{
out.close();//스트림닫기(수도꼭지잠그기)
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}
}
ex> OutputStreamWriter
package test01.node;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.io.OutputStreamWriter;
public class Test04_Writer
{
public static void main(String[] args)
{
//OutputStreamWriter(OutputStream out)
//화면과 연결된 출력스트림객체 얻어오기
OutputStream out=System.out;
//화면으로 데이터를 출력하기위한 2바이트 출력스트림 생성하기
Writer wt=new OutputStreamWriter(out);
//void write(char[] cbuf)
char ch[]={'한','글','사','랑'};
try{
//char배열 화면에 출력하기
wt.write(ch);
wt.write("아리랑 아리랑");
//스트림닫기
wt.close();
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}
ex> FileWriter 파일에 데이터를 출력하기 위한 2바이트 처리 스트림 클래스
package test01.node;
import java.io.FileWriter;
import java.io.IOException;
public class Test05_FileWriter
{
public static void main(String[] args)
{
FileWriter fw=null;
try
{
//test.txt파일에 2바이트단위로 데이터를 출력하기위한 스트림 생성
//fw=new FileWriter("test.txt");
//new FileWriter("출력할파일명",추가모드로 열건지);
//test.txt파일이 존재하면 파일뒤에 데이터가 추가됨
fw=new FileWriter("test.txt",true);
//문자열을 파일로 출력(저장하기)
fw.write("안녕하세요!\r\n");
fw.write("제이름은 이길동입니다.\r\n");
fw.write("밥 먹으러 가요~!\r\n");
System.out.println("파일로 저장 성공!");
}catch(IOException ie){
System.out.println(ie.getMessage());
}finally{
try{
if(fw!=null) fw.close();
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}
}
ex>FileReader
package test01.node;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test06_FileReader
{
public static void main(String[] args)
{
FileReader fr=null;
try
{
//test.txt파일에서 2바이트단위로 데이터를 읽어오기위한 스트림객체생성
fr=new FileReader("test.txt");
while(true)
{
//파일에서 글자하나(2바이트) 읽어오기.스트림의끝(파일끝)에
//도달하면 read메소드는 -1을 반환한다.
int n=fr.read();
if(n==-1) break;//파일끝이면 반복문 끝내기
//파일에서 읽어온 글자를 화면에 출력하기
System.out.print((char)n);
}
}catch(FileNotFoundException fe){
System.out.println(fe.getMessage());
}catch(IOException ie){
System.out.println(ie.getMessage());
}finally{
try{
if(fr!=null) fr.close();
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}
}
ex> FileOutputStream
package test01.node;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test07_FileOutputStream
{
public static void main(String[] args) {
FileOutputStream fos=null;
try
{
//파일에서 데이터를 읽어오기위한 1바이트 처리 스트림생성
fos=new FileOutputStream("data.dat");
//public void write(byte[] b,int off,int len) throws IOException
byte []b={65,66,67,68,69,70};
//b배열 0번째부터 3개를 파일로 저장하기
fos.write(b,0,3);
String str="hello";
fos.write(str.getBytes());
fos.close();
System.out.println("파일로 저장 성공!");
}catch(FileNotFoundException fe){
System.out.println(fe.getMessage());
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}
package test01.node;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Test08_FileInputStream
{
public static void main(String[] args)
{
FileInputStream fis=null;
try
{
//파일에서 데이터를 읽어오기위한 1바이트 처리 스트림객체 생성
fis=new FileInputStream("data.dat");
//while(true){
// //파일에서 1바이트 읽어오기
// int n=fis.read();
// //파일끝이면 빠져나가기
// if(n==-1) break;
// //읽어온 데이터 화면에 출력하기
// System.out.print((char)n);
//}
byte[] b=new byte[1024];
while(true)
{
//파일에서 읽어와 b배열에 저장,n에는 읽어온 바이트수크기가 저장됨
int n=fis.read(b);
if(n==-1) break;//파일끝이면 빠져나가기
//배열을 문자열객체로 변환하기
String str=new String(b);
//화면에 출력하기
System.out.println(str);
}
fis.close();//스트림 닫기
}catch(FileNotFoundException fe){
System.out.println(fe.getMessage());
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}
ex> 키보드로 5명의 이름과 전화번호를 입력받고 입력받은 데이터를 파일로 저장해보세요
package test01.node;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Quiz01
{
public static void main(String[] args)
{
//파일에 저장하기 위한 스트림객체
FileWriter fw=null;
//파일에서 읽어오기 위한 스트림객체
FileReader fr=null;
//키보드로 입력받기 위한 객체
Scanner scan=new Scanner(System.in);
try
{
//파일에 저장하기 위한 2바이트 처리스트림객체 생성
fw=new FileWriter("phone.txt");
//키보드로 다섯명 데이터 입력받아 파일로 저장하기
for(int i=1;i<=2;i++)
{
//키보드로 입력받기
System.out.println("이름입력");
String name=scan.next();
System.out.println("전화입력");
String phone=scan.next();
//파일로 저장하기
fw.write(name+"," +phone +"\r\n");
}
System.out.println("파일로 저장성공!");
fw.close();//스트림닫기
//파일에서 읽어오기 위한 2바이트 처리 스트림객체
fr=new FileReader("phone.txt");
//--while(true){
// int n=fr.read();
// if(n==-1) break;
// System.out.print((char)n);
//}--
int n=0;
while((n=fr.read())!=-1){
System.out.print((char)n);
}
fr.close();
}catch(FileNotFoundException fe){
System.out.println("해당 파일이 존재하지 않아요!");
}catch(IOException fe){
System.out.println(fe.getMessage());
}
}
}
ex> 파일복사하는 프로그램을 작성해 보세요.
예)
원본파일명:aa.txt ( aa.txt 만 만들어 놓은 상태에서 실행하면 copy.txt 파일이 만들어 진다. )
복사본파일명:copy.txt
==>aa.txt파일을 copy.txt파일로 복사 (1바이트 처리스트림 사용해서)
package test01.node;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Quiz02
{
public static void main(String[] args)
{
FileInputStream fis=null;
FileOutputStream fos=null;
try
{
//원본파일을 읽어오기위한 스트림객체
fis=new FileInputStream("aa.txt");
//복사본파일에 출력하기위한 스트림객체
fos=new FileOutputStream("copy.txt");
byte []b=new byte[1024];
long fileSize=0;
while(true)
{
//파일에서 데이터 읽어와 b배열에 저장
//n에는 읽어온 바이트수크기가 저장됨
int n=fis.read(b);
if(n==-1) break;
//b배열의 0번째 위치부터 n개만큼만 파일로 저장
fos.write(b,0,n);
//파일크기 구하기
fileSize+=n;
}
System.out.println(fileSize + "bytes 크기의 파일복사성공!");
//스트림닫기
fos.close();
fis.close();
// 1BYTE씩 읽기.
//-- while(true){
// //원본파일에서 1바이트 읽어오기
// int n=fis.read();
// if(n==-1) break;//파일끝이면 반복문 끝내기
// //복사본파일에 1바이트 출력하기
// fos.write(n);
//}
//System.out.println("파일복사성공!");
//스트림닫기
//fos.close();fis.close();
//--/
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}
ex> phone.txt 파일을 BufferedReader객체를 이용해서 한줄씩 읽어와 화면에 출력해 보세요.
package test01.node;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class Quiz03
{
public static void main(String[] args)
{
// InputStream in=new FileInputStream("phone.txt");
//Reader rd=new InputStreamReader(in);
//BufferedReader br=new BufferedReader(rd);
//
try
{
Reader rd=new FileReader("phone.txt");
BufferedReader br=new BufferedReader(rd);
//-- while(true){
// String line=br.readLine();
// if(line==null) break;
// System.out.println(line);
//}--
String line=null;
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
}catch(IOException ie){
System.out.println(ie.getMessage());
}
}
}