12일차 : IO, 입출력

BufferedOutputStream

import java.io.*; class BufferedOutputStream01 { public static void main(String[] args) { //public BufferedOutputStream(OutputStream out) //화면에 출력하기 위한 버퍼(바이트 배열)기능이 강화된 객체 생성 //OutputStream out=System.out; BufferedOutputStream bos=new BufferedOutputStream(System.out);//System.out : 모니터로 연결 //아래처럼 버퍼의 크기(1024바이트)를 지정할 수 있다. //BufferedOutputStream bos=new BufferedOutputStream(System.out,1024); byte[] b={65,66,67,68,69,70}; try{ bos.write(b,0,5);//5byte bos.flush(); bos.close(); }catch(IOException ie){ System.out.println(ie.getMessage()); } } } /* [결과] ABCDE */

 

 

 

 

BufferedOutputStream - 데이터 파일로 저장

import java.io.*; class BufferedOutputStream02{ public static void main(String[] args) { //public BufferedOutputStream (OutputStream out) - 파일과 연결해주고 싶으면 FileOutputStream byte[] b={65,66,67,68,69,70}; try{ OutputStream out=new FileOutputStream("buf.dat"); //파일로 출력하기 위한 스트림 객체 생성 BufferedOutputStream bos=new BufferedOutputStream(out);//System.out : 모니터로 연결, out : 파일과 연결 bos.write(b,0,5); //b배열의 데이터가 파일로 저장됨 bos.flush(); bos.close(); System.out.println("데이터를 파일로 저장 성공!"); }catch(IOException ie){ System.out.println(ie.getMessage()); } } }

 

 

 

BufferedReader - 한 줄 Line 입력

import java.io.*; class BufferedReader03 { public static void main(String[] args) { //public BufferedReader (Reader in) //InputStreamReader (InputStream in) //키보드로부터 읽어오기 위한 1바이트 처리 스트림 얻어오기 InputStream in=System.in; //1바이트 처리 스트림을 2바이트 처리 스트림으로 변환하기 Reader rd=new InputStreamReader(in); //2바이트 처리 스트림을 버퍼기능을 향상시킨 스트림 객체로 포장하기 BufferedReader br=new BufferedReader(rd); //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); => 이렇게 한 줄로 나열하여 쓸 수 있다 //public String readLine() throws IOException System.out.println("한 줄 입력"); try{ String line=br.readLine(); System.out.println("Line: "+line); br.close(); //스트림닫기 }catch(IOException ie){ System.out.println(ie.getMessage()); } } }

 

 

 

DataOutputStream - 기본자료형을 파일로 출력

import java.io.*; class DataOutputStream01 { public static void main(String[] args) { try{ //기본 자료형을 파일로 출력하기 위한 스트림 객체 생성 DataOutputStream dos=new DataOutputStream(new FileOutputStream("data.dat")); int a=10; byte b=100; boolean c=false; float d=4.5f; double e=3.4; String f="hello"; dos.writeInt(a); //int형을 파일로 저장(실제로 자료형의 크기(4바이트)만큼 저장된다.) dos.writeByte(b); //byte형을 파일로 저장(파일에 1바이트로 저장) dos.writeBoolean(c); dos.writeFloat(d); dos.writeDouble(e); dos.writeUTF(f); System.out.println("파일로 저장 성공!"); dos.close(); }catch(FileNotFoundException fe){ System.out.println(fe.getMessage()); }catch(IOException ie){ System.out.println(ie.getMessage()); } }

}

 

 

 

 

DataInputStream - 데이터의 자료형 크기 만큼 읽어오기


import java.io.*;
class DataInputStream02 {
	public static void main(String[] args) {
		//data.dat파일에서 데이터를 자료형의 크기만큼 읽어오기 위한 스트림 객체 생성
		try{
			DataInputStream dis=new DataInputStream(new FileInputStream("data.dat"));
			//파일에서 읽어올 때는 저장된 자료형의 순서와 반드시 일치해야 한다.
			//파일에서 int형의 크기(4바이트)만큼 읽어와 a에 저장
			int a=dis.readInt();
			byte b=dis.readByte();
			boolean c=dis.readBoolean();
			float d=dis.readFloat();
			double e=dis.readDouble();
			String f=dis.readUTF();
			System.out.println("파일에 저장된 데이터");
			System.out.println("a: "+a);
			System.out.println("b: "+b);
			System.out.println("c: "+c);
			System.out.println("d: "+d);
			System.out.println("e: "+e);
			System.out.println("f: "+f);
			dis.close();
		}catch(FileNotFoundException fe){
			System.out.println(fe.getMessage());
		}catch(IOException ie){
			System.out.println(ie.getMessage());
		}
	}
}

 

 

 

 FileOutputStream - b배열의 0번째 위치에서 b배열의 크기(5)만큼 파일로 저장하기

import java.io.*; class FileOutputStream01{ public static void main(String[] args) { //public FileOutputStream(String name) throws FileNotFoundException FileOutputStream fout=null; //FileOutputSream객체를 선언(반드시 객체 선언) try{ //파일에 데이터를 출력할 수 있는 1바이트 처리 스트림객체 생성 fout=new FileOutputStream("test.dat"); //public void write(byte[] b,int off, int len) throws IOExecption byte[] b={65,66,67,68,69}; //b배열의 0번째 위치에서 b배열의 크기(5)만큼 파일로 저장하기 fout.write(b, 0, b.length); fout.flush();//버퍼가 다 차지 않아도 데이터 출력하기 System.out.println("파일로 저장 성공!"); }catch(FileNotFoundException fe){ System.out.println(fe.getMessage()); }catch(IOException ie){ System.out.println(ie.getMessage()); }finally{ try{ if(fout!=null) fout.close();//파일 스트림 닫기 }catch(IOException ie){ System.out.println(ie.getMessage()); } } } }

 

 

 

 

FileInputStream - 파일에서 1바이트단위로 데이터를 읽어오기


import java.io.*;
class FileInputStream02{
	public static void main(String[] args) 	{
		//public FileInputStream(String name) throws FileNotFoundException
		FileInputStream fin=null;
		try{
			//파일에서 1바이트단위로 데이터를 읽어오기위한 스트림객체 생성
			fin=new FileInputStream("test.dat");

			//////// 방법1 /////////////////////////////
			/*
			//public int read() throws IOException
			while(true){
				//파일에서 1바이트 읽어와 n에 저장
				int n=fin.read();
				if(n==-1) //파일의 끝에 도달한 경우
					break;//루프끝내기
				System.out.print((char)n);//n을 화면에 출력
			}*/

			///////// 방법2 //////////////////////////////
			/*int n=0;
			while((n=fin.read())!=-1){
				System.out.print((char)n);
			}*/

			//public int read(byte[] b,int off, int len)	throws IOException
			byte[]d =new byte[100];
			int n=0;	//n에 저장되어있는 것은 5byte
			while(true){
				//파일에서 읽어와 b배열에 저장. n에는 읽어온 바이트 수 크기가 저장
				n=fin.read(d,0,d.length);
				if(n==-1){	//파일 끝에 도달해서 더이상 데이터가 없으면 루프 끝내기
					break;
				}
				//d배열의 0번 째에서 n만큼 (읽어온 바이트 수 크기 만큼)화면에 출력하기
				System.out.write(d, 0, n);
				System.out.flush();
			}
		}catch(FileNotFoundException fe){
			System.out.println(fe.getMessage());
		}catch(IOException ie){
			System.out.println(ie.getMessage());
		}finally{
			try{
				if(fin!=null) fin.close();//파일스트림 닫기
			}catch(IOException ie){
				System.out.println(ie.getMessage());
			}
		}

	}
}

 

PrintWriter - 화면에 출력하기

import java.io.*; //아래의 결과를 화면으로 출력되도록 수정해 보세요~~ class PrintWriter01 { public static void main(String[] args) { //화면에 출력하기 위한 스트림 객체 생성 PrintWriter pw=new PrintWriter (System. out); pw.println("안녕하세요!"); pw.println("만나서 반가워요~"); pw.close(); System.out.println("파일로 저장 성공!"); } } /* 파일로 생성 try{ //파일에 출력하기 위한 스트림 객체 생성 PrintWriter pw=new PrintWriter("print.txt"); pw.println("안녕하세요!"); pw.println("만나서 반가워요~"); pw.close(); System.out.println("파일로 저장 성공!"); }catch(FileNotFoundException fe){ System.out.println(fe.getMessage()); } } } */

 

 

 

 

Quiz01


/*
	파일복사하는 프로그램을 작성해 보세요.
	FileInputStream,FileOutputStream 사용
	
	원본          복사본
	test.dat ===> copy.dat
*/
import java.util.Scanner;
import java.io.*;
class Quiz01_1{
	public static void main(String[] args)	{
		Scanner scan=new Scanner(System.in);
		System.out.println("원본파일명");
		String orgFileName=scan.next();
		System.out.println("복사될파일명");
		String copyFileName=scan.next();

		FileInputStream fin=null;
		FileOutputStream fout=null;
		try{
			//원본파일을 읽어오기위한 파일스트림객체
			fin=new FileInputStream(orgFileName);
			//복사본파일에 저장하기 위한 파일스트림객체
			fout=new FileOutputStream(copyFileName);
			byte[] b=new byte[100];
			int n=0;
			int fileSize=0;//전체 파일크기
			while(true){
				//원본파일읽어와 b배열에 저장하기
				n=fin.read(b,0,b.length);
				if(n==-1) break;
				//읽어온 데이터를 복사본파일에 저장하기
				fout.write(b,0,n);
				fileSize+=n;
			}
			fin.close();
			fout.close();
			System.out.println("복사된 파일크기:"+ fileSize +"bytes");
			System.out.println(copyFileName+"으로 복사성공!");

		}catch(FileNotFoundException fe){
			System.out.println(fe.getMessage());
		}catch(IOException ie){
			System.out.println(ie.getMessage());
		}
	}
}

 

Quiz02

/* BufferedReader 를 사용해서 test.txt파일을 한 줄씩 읽어와 화면에 출력해 보세요. */ import java.io.*; class Quiz02{ public static void main(String[] args) { try{ //test.txt파일에서 데이터를 읽어오기 위한 2바이트 처리 스트림 객체 생성 BufferedReader in = new BufferedReader(new FileReader("c:\\JAVA\\11일차_예외처리_IO\\test.txt")); String line=null; while((line=in.readLine())!=null){//파일에서 한 줄 읽어오기(null이면 파일 끝) System.out.println(line);//화면에 출력하기 } in.close(); }catch(FileNotFoundException fe){ System.out.println(fe.getMessage()); }catch(IOException ie){ System.out.println(ie.getMessage()); } } }

 

 

 

 

Quiz03

/* 다섯 명의 학생 이름, 전화번호를 키보드로 입력력받아 파일(phone.txt)에 저장해 보세요. ##파일에 저장된 형태 홍길동, 010-111-1234 김아무, 010-222-3333 */ import java.io.*; import java.util.Scanner; class Quiz03 { public static void main(String[] args) { //Scanner scan=new Scanner (System.in); try{ //키보드로 데이터를 읽어오기 위한 입력스트림객체 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //파일에 저장하기 위한 출력 스트림 객체 PrintWriter in=new PrintWriter("phone.txt"); //다섯명 데이터 입력받아 파일로 저장하기 for(int i=1; i<=5; i++){ System.out.println("학생의 이름을 입력하세요."); String name=br.readLine(); System.out.println("전화번호를 입력하세요."); String phone=br.readLine(); //파일로 저장 in.println(name+","+phone+"\r\n"); } br.close(); in.close(); System.out.println("파일로 저장 성공!"); }catch(FileNotFoundException fe){ System.out.println(fe.getMessage()); }catch(IOException ie){ System.out.println(ie.getMessage()); } } }

 

 

Quiz04

/* 1. 학생의 이름,국어,영어점수를 키보드로 입력받아 총점,평균을 계산후 파일에 저장하기 Scanner,DataOutputStream 사용 2. 파일에 저장된 이름,국어,영어,총점,평균을 읽어와 화면에 출력하기 */ import java.io.*; import java.util.Scanner; class Quiz04_1{ static Scanner scan=new Scanner(System.in); public static void main(String[] args) { while(true){ System.out.println("1.점수입력 2.성적보기 3.종료"); int n=scan.nextInt(); switch(n){ case 1:saveData();break; case 2:readData();break; case 3:System.exit(0);break; default:System.out.println("잘못입력"); } } } public static void saveData(){ try{ //파일에 데이터를 추가할 수 있는 모드로 스트림객체 생성 DataOutputStream dos=new DataOutputStream(new FileOutputStream("stu.dat",true)); System.out.print("이름:"); String name=scan.next(); System.out.print("국어:"); int kor=scan.nextInt(); System.out.print("영어:"); int eng=scan.nextInt(); int tot=kor+eng; double ave=tot/2.0; //입력받은 데이터를 파일에 저장하기 dos.writeUTF(name); dos.writeInt(kor); dos.writeInt(eng); dos.writeInt(tot); dos.writeDouble(ave); dos.close(); System.out.println("저장성공!"); }catch(Exception e){ System.out.println(e.getMessage()); } } public static void readData(){ DataInputStream dis=null; try{ dis=new DataInputStream(new FileInputStream("stu.dat")); System.out.println("이름\t국어\t영어\t총점\t평균"); while(true){ //파일에 저장된 순서대로 데이터 읽어오기 String name=dis.readUTF(); int kor=dis.readInt(); int eng=dis.readInt(); int tot=dis.readInt(); double ave=dis.readDouble(); System.out.println(name+"\t"+kor+"\t"+eng+"\t"+tot+"\t"+ave); } }catch(FileNotFoundException fe){ System.out.println(fe.getMessage()); }catch(EOFException e){ System.out.println("모든 정보 출력됨"); }catch(IOException ie){ System.out.println(ie.getMessage()); }finally{ try{ if(dis!=null) dis.close(); }catch(IOException ie){} } } }

 

 

 

 

 

[ 과 제 ]