[JAVA] 자바 - DataOutputStream / BufferedReader 버퍼 크기 주기
by mini_min[JAVA]
자바 - DataOutputStream / BufferedReader 버퍼 크기 주기
✔️ DataOutputStream
- 기본 JAVA 데이터 유형을 플랫폼에 독립적인 방법으로 기본 입력 스트림에서 읽을 수 있다.
- 필터 스트림이기 때문에 다른 입력 스트림을 생성자 인자로 받아서 객체로 생성한다! (버퍼와 동일)
try ( DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt")) ) { dos.writeUTF("서울"); dos.writeByte(10); dos.writeChar('A'); dos.writeInt(50); dos.writeUTF("대한"); System.out.println("파일 저장 완료..."); } catch (Exception e) { e.printStackTrace(); }
🔒 DataInputStream : 내용 받아서 출력
- 기본 자료형으로 입력 가능
- 더 이상 읽을 내용이 없으면 EOFException 이 발생한다.
try (DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"))){ String s1 = dis.readUTF(); byte b = dis.readByte(); char c = dis.readChar(); int i = dis.readInt(); String s2 = dis.readUTF(); // 위치에 따라 달라짐 (이상한 현상) 순서 맞춰야한다. System.out.println(s1); System.out.println(b); System.out.println(c); System.out.println(i); System.out.println(s2); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
💡 DataInputStream 사용할 때, Input 되는 순서가 중요하다.
✔️ BufferedReader 버퍼 크기 설정
- BufferedOutputStream 에서 기본 버퍼 크기를 8192로 설정해서, 따로 버퍼 크기를 줄 수 있다.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String source, dest; byte[] b = new byte[BUFFER_SIZE]; int len; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { System.out.println("원본 파일명 ? "); source = br.readLine(); System.out.println("복사본 파일명 ? "); dest = br.readLine(); bis = new BufferedInputStream(new FileInputStream(source)); bos = new BufferedOutputStream(new FileOutputStream(dest), BUFFER_SIZE); // 기본이 8192 가 버퍼의 기본 크기지만, 따로 줄 수 있음. while((len=bis.read(b)) != -1) { bos.write(b, 0, len); } bos.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if(bis!=null) { try { bis.close(); } catch (Exception e2) { } } if(bos!=null) { try { bos.close(); } catch (Exception e2) { } } }
💡 byte[] b 배열에 버퍼 크기를 집어 넣음
블로그의 정보
개발자 미니민의 개발로그
mini_min