본문 바로가기

Java Programming

Stream - Byte Stream

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
Stream이 무엇인지에 대한 전체적인 개념은 짚고 넘어갔는데요, 스트림에도 많은 종류의 스트림들이 존재 했습니다. 그중에 가장 스트림의 기본이 되는 Byte Stream을 먼저 배워보았습니다.
Byte Streams
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.

There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.

프로그램에서는 input과 output을 8비트(즉, 1 바이트)로 표현하는 byte stream을 사용합니다. 모든 byte stream 클래스들은InputStream과 OutputStream으로 부터 전해져옵니다.

많은 byte stream 클래스들이 있다. byte stream이 어떻게 작동하는지 설명하는지는, FileInputStream 과 FileOutputSteam같은 file I/O byte Stream에 초점을 맞추도록 하겠다.  다른 종류의 바이트스트림은 거의 같은 방법으로 사용된다.

튜토리얼에 있는 소스를 코딩해봤습니다.

단순하게 텍스트 파일을 입력받아서 다른 파일명의 똑같은 내용의 텍스트 파일로 만들어주는 코드입니다.

위에 try 구문을 보면 c라는 이름을 가진 int 값의 숫자가 선언된것을 볼수 있는데 while 문에 있는 read() 메소드는 int의 값을 리턴합니다. 실제로 c라는 인티져 값으로 들어가는데는 무리가 없는데요. 문제는 8바이트씩 읽는 byte 스트림의 영역을 벗어나는 값이 입력이 된다면 어떻게 될까 하는 것인데요. 그다지 신경쓸필요가 없습니다. c 의 값은 byte 값의 영역을 벗어나지를 않습니다. 따라서 (byte) in.read() 이런식으로 캐스팅을 해줘도 에러가 발생하지 않습니다 ^^

Always Close Streams

Closing a stream when it's no longer needed is very important — so important that CopyBytes uses a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks.

One possible error is that CopyBytes was unable to open one or both files. When that happens, the stream variable corresponding to the file never changes from its initial null value. That's why CopyBytes makes sure that each stream variable contains an object reference before invoking close.


다음으로 주목해야 할 부분은 finally 구문 입니다. 항상 Close() 메소드를 사용하여 스트림 객체를 종료 시켜 줘야 한다는 건데요. 처음 예외처리를 공부할때 finally 구문이 왜 존재할 것인가? 라고 의문을 가졌었는데 이렇게 입출력하는 스트림 객체를 닫아주는 때에도 사용 한다는걸 알았습니다.

왜 꼭 종료를 해줘야 하는것인가? 그건은 avoid serious resource leaks 라는 문장에서 알 수 있습니다. 말그대로 심각한 리소스의 누출을 피할 수 있다는 건데요. 실제로 IO 같은 경우에는 자체적으로 자가 PC 에서만 사용할 수도 있지만 수많은 네트워크로 연결된 이상 이렇게 입출력하는때에 오류가 발생한후에 입출력객체를 닫아 주지 않으면 보안상의 문제가 생길수 있고.. 뭐 그런 문제같은데.. 실제로 본적이 없어서 잘은 모르겠습니다 ^^;; 추측일 뿐임으로 인용하지 마시기 바랍니다!!

When Not to Use Byte Streams

CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. Since xanadu.txt contains character data, the best approach is to use character streams, as discussed in the next section. There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O.

So why talk about byte streams? Because all other stream types are built on byte streams.

바이트 스트림은 모든 스트림 클래스의 근원이 됩니다만, 다른 방법의 스트림 클래스들이 있기때문에 다른 방법을 사용하는것이 좋다네요. 다음에는 Character Stream에 대해서 배우도록 하겠습니다 +_+