본문 바로가기
오래된글/Java

Character and Byte Streams

by Andrew's Akashic Records 2018. 4. 7.
728x90

java.io 패키지는 Unicode와 Unicode가 아닌 Text의 Character Stream과 Byte Stream 변환을 허용하는 클래스를 제공한다. InputStreamReader 클래스로 Charater Stream에서 Byte Stream으로 변환할 수 있다. 또 OutputStreamWriter 클래스를 이용하여 Byte Stream을 Charater Stream으로 변환할 수도 있다.


InputStreamReader와 OutputStreamWriter 객체를 생성할 때, 변환을 원하는 byte encoding을 지정하면된다. 예를 들어 UTF-8 encoding Unicode로 Text파일을 변환하고 싶으면 아래와 같이 InputStreamReader을 생성한다.

FileInputStream fis = new FileInputStream("test.txt");

InputStreamReader isr = new InputStreamReader(fis, "UTF8");


만일 encoding 스타일을 지정하지 않으면 InpuStreamReader와 OutputStreamWriter는 디폴트 encoding을 사용한다. 다음과 같이 현재 시스템의 디폴트 encoding을 알아볼 수 있다.

InputStreamReader defaultReader = new InputStreamReader(fis);

String defaultEncoding = defaultReader.getEncoding();


이번 예제을 통해 우리는 InputStreamReader와 OutputStreamWriter 클래스을 이용한 character-set 변환을 볼 것이다. 예제 파일은 StreamConverter.javad이며, 이 프로그램은 일본어 Character(Sun은 한글을 무시하나 봅니다. 한글자료는 하나도 없습니다.)을 출력한다.

import java.io.*;

import java.util.*;

public class StreamConverter {

static void writeOutput(String str) {

try {

FileOutputStream fos = new FileOutputStream("test.txt");

Writer out = new OutputStreamWriter(fos, "UTF8");

out.write(str);

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

static String readInput() {

StringBuffer buffer = new StringBuffer();

try {

FileInputStream fis = new FileInputStream("test.txt");

InputStreamReader isr = new InputStreamReader(fis, "UTF8");

Reader in = new BufferedReader(isr);

int ch;

while ((ch = in.read()) > -1) {

buffer.append((char)ch);

}

in.close();

return buffer.toString();

} catch (IOException e) {

e.printStackTrace();

return null;

}

}

public static void main(String[] args) {

String jaString =

new String("u65e5u672cu8a9eu6587u5b57u5217");

writeOutput(jaString);

String inputString = readInput();

String displayString = jaString + " " + inputString;

new ShowString(displayString, "Conversion Demo");

}

}


import java.awt.*;

class ShowString extends Frame {

FontMetrics fontM;

String outString;

ShowString (String target, String title) {

setTitle(title);

outString = target;

Font font = new Font("Monospaced", Font.PLAIN, 36);

fontM = getFontMetrics(font);

setFont(font);

int size = 0;

for (int i = 0; i < outString.length(); i++) {

size += fontM.charWidth(outString.charAt(i));

}

size += 24;

setSize(size, fontM.getHeight() + 60);

setLocation(getSize().width/2, getSize().height/2);

show();

}

public void paint(Graphics g) {

Insets insets = getInsets();

int x = insets.left;

int y = insets.top;

g.drawString(outString, x + 6, y + fontM.getAscent() + 14);

}

}



StreamConverter프로그램은 String 객체로부터 FileOutputStream으로 UTF-8로 변환된 Byte을 저장한다.

static void writeOutput(String str) {

try {

FileOutputStream fos = new FileOutputStream("test.txt");

Writer out = new OutputStreamWriter(fos, "UTF8");

out.write(str);

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

readInput 메소드는 writeOutput메소드에서 생성된 파일을 UTF-8로 인코딩된 Byte로 읽는다. InputStreamReader 객체는 Unicode로 UTF-8 Byte을 변환하고 이 결과를 String 객체에 담는다.

static String readInput() {

StringBuffer buffer = new StringBuffer();

try {

FileInputStream fis = new FileInputStream("test.txt");

InputStreamReader isr = new InputStreamReader(fis,

"UTF8");

Reader in = new BufferedReader(isr);

int ch;

while ((ch = in.read()) > -1) {

buffer.append((char)ch);

}

in.close();

return buffer.toString();

} catch (IOException e) {

e.printStackTrace();

return null;

}

}

StreamConverter 프로그램에서 UTF-8 encoding으로 바이트 파일을 생성하는 메소드는 writeOutput이며, readIniput 메소드는 Unicode로 Byte을 변환하여 파일을 읽는다.


728x90