Java에서 한글 인코딩 / 디코딩 관련 질문입니다.

cococo의 이미지

우선...코드를 먼저 보시는 게 설명이 쉬울 듯 하여, 코드를 올립니다.

	String fileEncoding=System.getProperty("file.encoding");
        System.out.println("file.encoding = "+fileEncoding);
 
        String Encoding = "한글";
        try {
        	String toBinaryRaw = new String(Encoding.getBytes() );
		System.out.println("Binary Raw Data:" + toBinaryRaw );
		ShowAllByte( toBinaryRaw );
        	String toISO_8859 = new String(Encoding.getBytes(),"ISO-8859-1");
		System.out.println("ISO-8859-1 Encoding : " + toISO_8859 );
		ShowAllByte( toISO_8859 );
		String toUtf_8 = new String(Encoding.getBytes(),"utf-8");
		System.out.println("UTF-8 Encoding : " + toUtf_8);
		ShowAllByte( toUtf_8 );
		String toEUCKR = new String(Encoding.getBytes(),"euc-kr");
		System.out.println("toEUCKR Encoding : " + toEUCKR );
		ShowAllByte( toEUCKR );
		String toUTF8_EUCKR = new String( Encoding.getBytes("utf-8"),"euc-kr");
		System.out.println("toUTF8_EUCKR Encoding : " + toUTF8_EUCKR );
		ShowAllByte( toUTF8_EUCKR  );
		String toksc5601 = new String(Encoding.getBytes(),"KSC5601");
		System.out.println("KSC5601 Encoding : " + toksc5601);			
		ShowAllByte( toksc5601 );
		String toms949 = new String(Encoding.getBytes(),"ms949");
		System.out.println("MS949 Encoding : " + toms949);			
		ShowAllByte( toms949 );
 
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}

보시는 바와 같이, 한글 인코딩 / 디코딩 테스트를 위한 코드입니다.
이클립스 환경은 UTF-8로 되어 있습니다. 그래서 실행시키면

file.encoding = utf-8
Binary Raw Data:한글
Size: 6 Byte: [0xed 0x95 0x9c 0xea 0xb8 0x80 )
ISO-8859-1 Encoding : 한글
Size: 12 Byte: [0xc3 0xad 0xc2 0x95 0xc2 0x9c 0xc3 0xaa 0xc2 0xb8 0xc2 0x80 )
UTF-8 Encoding : 한글
Size: 6 Byte: [0xed 0x95 0x9c 0xea 0xb8 0x80 )
toEUCKR Encoding : ���
Size: 9 Byte: [0xef 0xbf 0xbd 0xef 0xbf 0xbd 0xef 0xbf 0xbd )
toUTF8_EUCKR Encoding : ���
Size: 9 Byte: [0xef 0xbf 0xbd 0xef 0xbf 0xbd 0xef 0xbf 0xbd )
KSC5601 Encoding : ���
Size: 9 Byte: [0xef 0xbf 0xbd 0xef 0xbf 0xbd 0xef 0xbf 0xbd )
MS949 Encoding : �쒓�
Size: 9 Byte: [0xef 0xbf 0xbd 0xec 0x92 0x93 0xef 0xbf 0xbd )

이와 같이 나옵니다.

1. 목적은 UTF-8 환경 한글을 TCP/IP로 전송하여 EUC-KR 환경에서 보는 겁니다. 단, Client:UTF-8 이고 Server:EUC-KR 이라서, Client쪽에서 UTF-8을 EUC-KR로 바꿔주려 합니다.

근데, 처음에 new String( Encoding.getBytes(), "EUC-KR"); 해도 자꾸 한글이 깨지길레, 아무래도 이상해서 Client에서 전송 전에 Binary값을 찍어 보니 위와 같은 결과를 얻었습니다.

저는 String( Encoding.getBytes(), "EUC-KR" ) 하면 6Byte의 UTF-8 "한글" 이 4Byte의 EUC-KR "한글" 로 바뀔 거라고 생각했는데, 실제로 찍어보니 6바이트가 아니라 9바이트가 됐네요?

저걸 new String( Encoding.getBytes("UTF-8"), "EUC-KR"); 로도 해 봤습니다만...마찬가지구요.

인터넷 뒤져보면 다른 분들은 단순히 String( text.getBytes( FromEncode ), ToEncode ) 만으로도 문제없이 사용하시는 듯 한데,
저는 뭐가 문제인지 모르겠습니다.

혹시 제가 이해 자체가 잘못되었다면 잘못된 부분을 언급해 주시면 감사하겠구요.
만일 비슷한 경우를 겪으셨거나, 혹은 조언이 있으시다면, 주저없이 알려 주시면 대단히 감사하겠습니다.

이상입니다. 좋은 저녁 되시기 바랍니다.

emptynote의 이미지

byte[] getBytes() 대신 byte[] getBytes(String charsetName) 를 이용하세요.

java API를 보시면
-----------
byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
----------------
이렇게 설명하고있습니다. 여기서 주목할점은 "the platform's default charset"입니다.

String(byte[] bytes, String charsetName) 에서 파라미터 bytes는 변환할려는 charsetName에 정확하게 일치해야합니다.

그래야 제대로 보여줄수있습니다.

그런데, "플랫폼 디폴트 문자셋"(the platform's default charset)으로 바이트 배열을 가져와서는

그것을 각각의 문자셋 String로 변환을 하기때문에 엉뚱하게 보이는것이 맞습니다.

cococo의 이미지


k9200544 님. 답변 감사드립니다. 그런 생각은 못 해 봤네요. 막연히 Encode/Decode 다 된다고 생각해서..

그럼, 자바는 Encode 함수는 없는 건가요?

언뜻 생각해도, Encode 함수가 없을 것 같지는 않은데요.

인터넷 뒤져보면 OutputStreamWrite() 같은건 Encode String 을 지정할 수 있다고 나오는데, 이 이야기는 [인코딩은 시스템 안팎으로 데이터가 드나들 때만 하면 된다] 라는 의미잖아요?

그런데, 이렇게 해 놨을 리가 없(?)다는 생각도 들구요.
프로그램 짤때 편의상 txt를 먼저 Encoding 한 다음에, 나중에 byte 단위로 서버에 보낼 거 같기도 하구요.
( 예를 들어 txt의 ByteSize를 구하려면, 인코딩 방식에 따라 ByteSize가 달라지니, 반드시 Encoding을 먼저 해야 ByteSize를 알 수 있잖아요. ㅡ,.ㅡ;; )
누군가가(?) 인코딩 함수를 구현해 버렸을 거 같기도 한데요. ( 막상 찾아보면 죄다 New String( txt.getByte()) 만 나오긴 합니다만. T_T )

이상입니다. 만일 제가 잘못 생각하고 있다면 지적 부탁드리구요, 좋은 하루 되시기 바랍니다.

행복은 희생없이는 얻을 수 없는 것인가?
시대는 불행없이는 넘을 수 없는 것인가?

익명 사용자의 이미지

(제생각엔)
그런 함수는 없을것 같습니다.
character set간의 변환을 string construction외에 따로 할 필요가 없을것 같습니다. 직접 작성하신 코드가 굳이 말하자면 그런 함수가 되지 않을까 합니다.

익명 사용자의 이미지

(제생각엔)
그런 함수는 없을것 같습니다.
character set간의 변환을 string construction외에 따로 할 필요가 없을것 같습니다. 직접 작성하신 코드가 굳이 말하자면 그런 함수가 되지 않을까 합니다.

익명 사용자의 이미지

new String( Encoding.getBytes("ISO-8859-1"),"euc-kr")

댓글 달기

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 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <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].
  • 사용할 수 있는 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>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <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].
  • You can use Textile markup to format text.
  • 사용할 수 있는 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>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <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].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 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>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.