본문 바로가기

Java Programming

Stream - Character Streams

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
낮에 알아본 Byte Stream 보다 딱 2배 큰 개념인 Character Stream에 대해서 조사를 해봤습니다. Byte Stream 이 한 바이트씩 주고 받는다면 Character Stream 같은경우에는 두 바이트씩 주고 받는 답니다. 일단은 튜토리얼 소스코드를 작성하였습니다.


CopyCharacters is very similar to CopyBytes. The most important difference is that CopyCharacters uses FileReader and FileWriter for input and output in place of FileInputStream and FileOutputStream. Notice that both CopyBytes and CopyCharacters use an int variable to read to and write from. However, in CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int variable holds a byte value in its last 8 bits.
이전에 사용하였던 FileInput(Output)Stream 클래스와는 달리 문자를 주고 받는 스트림 클래스인 FileWriter(Reader)를 사용하고 있다는 차이점을 볼 수가 있습니다. 마찬가지로 c라는 정수형 지역변수를 사용하여 16비트 단위로 문자열을 읽어 온다고 합니다. 하지만 소스만 봐서는 쉽게 알수 없기때문에 직접 테스트를 해보았습니다.

테스트 조건은 16비트로 되어있는 한글로만 기록되어 있는 test.txt 파일을 따로 만들어서 FileWriter 로 읽어들인 후에 while문에서 in.read() 메소드의 리턴값이 들어가는 변수 c를 문자형으로 캐스팅 하여 출력을 해보았습니다.

test.txt 파일은 내용입니다.

안녕 난 민이라고해
내안에 너희들있다~

아래는 테스트 한 결과입니다.

확실히 16바이트 단위로 읽어 들이고 있다는것을 확인할 수 있었습니다. print() 메소드를 사용하였을때는 원본과 똑같이 나오고, println() 메소드를 사용하였을때는 한글자씩 line terminator와 함께 출력이 되는것을 볼수 있었습니다.

Character Streams that Use Byte Streams

Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.

There are two general-purpose byte-to-character "bridge" streams: InputStreamReader and OutputStreamWriter. Use them to create character streams when there are no prepackaged character stream classes that meet your needs. The sockets lesson in the networking trail shows how to create character streams from the byte streams provided by socket classes.

Character Stream 은 Wrapper Stream 이라고 하는데요.. 이건 무슨 의미인고 하고 조사해보니 Character 스트림 그 자체가 역할을 수행한다기 보다는 Byte 스트림 클래스인 FileOutputStream을 내부적으로 사용한다는 겁니다. 결국은 Byte 스트림을 근간으로 수행을 한다는 거죠. 다른 큰단위의 스트림들도 이와 마찬가지 인것 같습니다.