버글버글

Java 수업 기록 (25) IO - InputStream 본문

java/java 수업 기록

Java 수업 기록 (25) IO - InputStream

Bugle 2022. 8. 17. 00:00
반응형

 

▶ IO 

▶ InputStream 

1. 바이트 입력 스트림

2. 입력 데이터 단위

   1) 1개 : int

   2) 여러 개 : byte[]

3. 모든 정보를 StringBuilder에 저장한 뒤 확인

* int read(byte[] b)
읽은 내용은 byte배열 b에  저장
읽은 바이트 수를 반환
읽은 내용이 없으면 -1 반환

 

예시) 아래 예시는 문자가 깨치게 출력 됨.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Main {
	
	public static void m1() {
		
		File file = new File("c:\\storage", "b1.bin");
		FileInputStream fis = null;
		
		try {
			
			fis = new FileInputStream(file);
			
			// 모든 정보를 StringBuilder에 저장한 뒤 확인
			StringBuilder sb = new StringBuilder();
			byte[] b = new byte[5];	// 5바이트씩 읽기 위해서 준비
			int readByte = 0;
						
			while((readByte = fis.read(b)) != -1) {
				sb.append(new String(b, 0, readByte));
			}
			
			// 문자를 바이트 스트림으로 읽었기 때문에 문제가 발생
			System.out.println(sb.toString());

			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fis != null) fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
        
        // Apple Mango 맛있��.

▶ InputStreamReader 

1. 바이트 입력스트림을 문자 입력 스트림으로 변환

예시)

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

		File file = new File("c:\\storage", "b2.bin");
		FileInputStream fis = null;
		InputStreamReader isr = null;
		
		try {
			
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis);
			
			StringBuilder sb = new StringBuilder();
			char[] cbuf = new char[5]; // 5글자씩 읽기 위해서
			int readCnt = 0;
			
			while((readCnt = isr.read(cbuf)) != -1) {
				sb.append(cbuf, 0, readCnt);
			}
			
			System.out.println(sb.toString());
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (isr != null) isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

 

▶ DataInputStream 

1. 변수를 그대로 입력 받음

예시)

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

		File file = new File("c:\\storage", "b3.dat");
		FileInputStream fis = null;
		DataInputStream dis = null;
		
		try {
			
			fis = new FileInputStream(file);
			dis = new DataInputStream(fis);
			
			String name = dis.readUTF();
			int age = dis.readInt();
			double height = dis.readDouble();
			
			System.out.println(name + ", " + age + ", " + height);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(dis != null) dis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

 

▶ ObjectInputStream 

1. 객체를 그대로 입력 받음

예시)

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.util.List;

		File file = new File("C:\\storage", "b4.dat");
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		
		try {
			
			fis = new FileInputStream(file);
			ois = new ObjectInputStream(fis);
			
			List<User> users = (List<User>)ois.readObject();	// 오류 뜨는게 맞음.
			User user = (User)ois.readObject();
			
			for(User u : users) {
				System.out.println(u);
				}
			System.out.println(user);
			
		} catch(ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ois != null) ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

나중에는 그냥 Exception으로 오류코드를 받아라. 지금은 교육중이니 예외 연습하기.

 

 

 

예제) eclipse-jee-2021-03-R-win32-x86_64.zip 복사하기.
복사할 파일명은 eclipse.zip

		File src = new File("c:\\GDJ\\installer", "eclipse-jee-2021-03-R-win32-x86_64.zip");
		File cpy = new File("c:\\GDJ\\installer", "eclipse.zip");
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		
		try {
			
			bis = new BufferedInputStream(new FileInputStream(src));
			bos = new BufferedOutputStream(new FileOutputStream(cpy));
			
			byte[] b = new byte[1024];	// 1KB
			int readByte = 0;
			
			while((readByte = bis.read(b)) != -1) {
				bos.write(b, 0, readByte);
			}
			
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(bos != null) bos.close();
				if(bis != null) bis.close();
			} catch(IOException e) {
				e.printStackTrace();
			}
		}

 

 

예제2)

		// 1. 폴더가 없으면 폴더 생성하기
		File dir = new File("c:\\storage");
		if(dir.exists() == false) {
			dir.mkdirs();
		}
		
		
		// 2. c:\gdj\installer에 있는 eclipse c:\storage로 복사
		File src = new File("c:\\GDJ\\installer", "eclipse.zip");
		File dst = new File("c:\\storage", src.getName());	// 같은 이름을 가져오겠다.
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		
		try {
			
			bis = new BufferedInputStream(new FileInputStream(src));
			bos = new BufferedOutputStream(new FileOutputStream(dst));
			
			byte[] b = new byte[1024];	// 1KB
			int readByte = 0;
			
			while((readByte = bis.read(b)) != -1) {
				bos.write(b, 0, readByte);
			}
			
			if(bos != null) bos.close();
			if(bis != null) bis.close();
			
			// 원본과 복사본의 크기가 동일하면 원본을 제거
			if(src.length() == dst.length()) {
				src.deleteOnExit();
			}
			
		} catch(IOException e) {
			e.printStackTrace();
		}

 

 

▶ 기타사항

스트림 관련 (Scanner 내부 동작?)

Scanner 없이 키보드를 통해서 문자를 입력받아, byte stream 으로 출력하기

		try {
			
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			
			System.out.print("입력 >>> ");
			String str = br.readLine();
			
			System.out.println(str);
			
			br.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}

 

반응형