[IO-4] outputstream, inputstream

seratpfk·2022년 8월 15일
0

JAVA

목록 보기
91/96

outputstream

  • 스트림을 이용해서 객체를 전송하려면 직렬화를 해야 한다.
  • 직렬화가 필요한 객체는 Serializable 인터페이스를 구현해야 한다.
  • Serializabe 인터페이스를 구현한 클래스는 serialVersionUID 필드가 필요하다.
public class User implements Serializable {
	private static final long serialVersionUID = -1830845902387248224L;
	private int userNo;
	private String name;
	private int age;
	public User(int userNo, String name, int age) {
		super();
		this.userNo = userNo;
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [userNo=" + userNo + ", name=" + name + ", age=" + age + "]";
	} 
}
  • b1.bin 파일과 연결되는 바이트 출력 스트림 생성
File file = new File("C:\\storage", "b1.bin");
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			// 출력할 데이터 (1개: int, 여러 개: byte[])
			int c = 'A';
			String str = "pple Mango 맛있다."; // 한글 3Byte, 영어 1Byte
			byte[] b = str.getBytes(StandardCharsets.UTF_8);  // str.getByte("UTF-8")
			// 출력
			fos.write(c);
			fos.write(b);
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fos != null) fos.close();
			} catch(IOException e) {
				e.printStackTrace();
			}
  • 출력 속도 향상을 위한 BufferedOutputStream
		File file = new File("C:\\storage", "b2.bin");
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		try {
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			String str = "안녕하세요 반갑습니다."; // 한글 3Byte, 공백과 마침표는 1Byte. 총 32Byte
			byte[] b = str.getBytes("UTF-8");
			bos.write(b);
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(bos != null) bos.close();
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
  • 변수를 그대로 출력하는 DataOutputStream
		File file = new File("C:\\storage", "b3.dat");
		FileOutputStream fos = null;
		DataOutputStream dos = null;
		try {
			fos = new FileOutputStream(file);
			dos = new DataOutputStream(fos);
			// 출력할 변수
			String name = "에밀리";
			int age = 30;
			double height = 165.5;
			// 출력
			dos.writeUTF(name);
			dos.writeInt(age);
			dos.writeDouble(height);
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(dos != null) dos.close();
			} catch(IOException e) {
				e.printStackTrace();
			}
		}

inputstream

  • 바이트 스트림
		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;
			// int read(byte[] b)
			// 읽은 내용은 byte배열 b에 저장
			// 읽은 바이트 수는 반환
			// 읽은 내용이 없으면 -1을 반환
			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();
			}
  • 바이트 입력스트림을 문자 입력 스트림으로 변환 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
		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
		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();
			}
		}

0개의 댓글