자바 버퍼 출력 스트림 관련 질문 드립니다.

익명 사용자의 이미지


먼저 출력버퍼 스트림은 버퍼가 꽉차야 출력이 되는걸로 알고있습니다 그래서 제가 인의적으로 조작하여

InputStream in = new FileInputStream("C:\\Temp\\test.txt");
OutputStream out = new FileOutputStream("C:\\Temp\\cpy.txt");

BufferedInputStream bin = new BufferedInputStream(in,1);
BufferedOutputStream bout = new BufferedOutputStream(out,1);


bDa = bin.read();

bout.write(bDa);

이런식으로 bDa에 받아서 파일에다 출력하려고하는데 문제는 파일 내용에 a 하나 넣어놓고
버퍼에 넣으면 a 하나만 있으니 꽉찰것이고 그럼 바로 파일로 줘야되는데
파일은 비워있습니다.
여기서 bout.write(bDa); 을 다시한번 밑에다 추가해주면 파일에다 복사가 됩니다...

버퍼가 꽉차야 출력이아니라 버퍼 이상의 값이 나와야 출력이 되는건가요?

익명 사용자의 이미지

자바 api 문서를 읽어보면 어디에도 버퍼가 꽉 차면 flush 한다고 되어 있지 않습니다. write 에 대한 설명은 다음과 같습니다.

Ordinarily this method stores bytes from the given array into this stream's buffer, flushing the buffer to the underlying output stream as needed. If the requested length is at least as large as this stream's buffer, however, then this method will flush the buffer and write the bytes directly to the underlying output stream. Thus redundant BufferedOutputStreams will not copy data unnecessarily.

"필요하면 (as needed)" 버퍼를 비웁니다. 또는 쓰라고 요쳥받은 데이터가 버퍼의 크기보다 큰 경우에는 버퍼를 비우고 그 다음에는 버퍼에 쓰지 않고 연결된(underlying) output stream 바로 씁니다."

BufferedOutputStreams을 사용하는 목적이 중요한 것이지 실제로 언제 flush가 되는지는 그리 중요하지 않습니다. 다시 말하자면 "필요하면"의 정확한 의미는 중요하지 않습니다. 그런 detail에 의존하는 프로그래밍은 바람직하지 않습니다.

 의 이미지

Buffer를 이용한 성능 향상 효과를 누리면서도 필요한 시점에는 flush가 확실히 일어나야만 하나요?
그러면 flush를 직접 호출하세요:

https://docs.oracle.com/javase/7/docs/api/java/io/BufferedOutputStream.html#flush()

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.