java 에서 utf-8 <---> euc-kr 변환하기

exsider의 이미지

utf-8 <---> euc-kr 간에 인코딩을 변환하는 프로그램을 java 로 만들려고 하는데요,
iconv 를 쓰면 쉘에서 간단하게 되겠지만 MS윈도우에서도 돌아가는게 필요하거든요.

대충 아래처럼 만들어봤는데 제대로 동작하지를 않습니다.

public class Test {
	/*
	 * 문자열의 인코딩을 변경한다.
	 * src : 바꿀 문자열
	 * from : 원래의 인코딩
	 * to : 바꿀 인코딩
	 * 바뀐 문자열을 리턴한다.
	 */
	public static String test (String src, String from, String to) 
								throws UnsupportedEncodingException {
		
		return new String(src.getBytes(from),to);
	}


	public static void main(String args[]) {

		String str = "가나다라 abcde";
		try {
			String result = Test.test(str, "UTF-8", "EUC-KR");
			System.out.println(result);
		} catch (UnsupportedEncodingException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
}

다음 명령으로 테스트했습니다.(현재 시스템 로케일은 utf-8 입니다.)
java Test | iconv -f euc-kr -t utf-8

테스트해보면 에러메시지가 뜹니다.
揶›占쏙옙占쏙옙占쏙옙iconv: 21 위치에 잘못된 입력 순서열이 있음

뭔가 다른 방법이 없을까요?

thinker0의 이미지

exsider wrote:

    String str = "가나다라 abcde";

이부분이 잘못 되었네요. 원래 코드에 등록되어있는 str은 MS949엔코딩으로 입력된 문자열 이지 않나요 ?

그걸 다시 EUC-KR로 바꾸면 잘못된것.

위의 코드가 정상적일려 면 str에 들어 있는 코드를 UTF-8에디터로 작업 하셔야 올바른 코드 입니다.

exsider의 이미지

이 소스코드는 리눅스 환경에서 로케일이 UTF-8 인 상태에서 이클립스로
만들었습니다. 따라서 소스코드 자체의 인코딩은 UTF-8 이고
str 문자열의 인코딩도 UTF-8 입니다.

정녕 자바로는 방법이 없는 건가요???

wafe의 이미지

인코딩이 utf-8인 자바 소스를 컴파일 하려면 javac 에 "-encoding utf-8" 옵션을 주어야 합니다.

Heejoon Lee

fender의 이미지

exsider wrote:
이 소스코드는 리눅스 환경에서 로케일이 UTF-8 인 상태에서 이클립스로
만들었습니다. 따라서 소스코드 자체의 인코딩은 UTF-8 이고
str 문자열의 인코딩도 UTF-8 입니다.

정녕 자바로는 방법이 없는 건가요???

인코딩하려는 문자열을 소스에 넣지 않고 인자값으로 넘겨 보세요. 자바 문제 보다는 '사불'로 보이네요 :)

----------------------------
[서명] 그놈 한국 사용자 모임 - 그놈에 대한 모든 것! - 게시판, IRC, 위키, 갤러리 등등...

dkkang의 이미지

Quote:
인코딩하려는 문자열을 소스에 넣지 않고 인자값으로 넘겨 보세요. 자바 문제 보다는 '사불'로 보이네요 :)

자의적으로 질문한 사람에 대해 판단하지 말고, 필요한 대답만 해주는 게 좋을 거 같네요.

lauria의 이미지

public void writeData( String data ) throws InvalidPacketException, UnsupportedEncodingException
{
byte dataArray[] = data.getBytes( dec );
byte write[] = new byte[ dataArray.length +2];
write[0] = shortToByte( (short) dataArray.length )[0];
write[1] = shortToByte( (short) dataArray.length )[1];
System.arraycopy( dataArray, 0, write, 2, dataArray.length );
writeData( write );
}

public String readString() throws InvalidPacketException
{
int len = readShort();
System.out.print( "readString() length : " + new Integer(len).toString() + "\r\n" );
if( len <= 0 ) return "";
String str = new String();
try
{
byte bt[] = new byte[len];
readData( readPosition, len, bt );
str = String.valueOf( new String( bt, dec) );
System.out.print( "readString() str : " + str + "\r\n" );
}
catch(UnsupportedEncodingException ex ) {}
return str;
}

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.