본문 바로가기

IT

한글 encoding 문제 (utf-8 => ms949 변환)

참고URL : EUC-KR에서 UTF-8로 파일 인코딩 변경


오늘 뜬금없이 전해진 비보.

저번달까진 잘 되던 파일전송(SAM파일) 프로그램이 수신측에서 오류를 냈다고.


아~ 그동안 우리쪽은 변경된것이 없단말이... 다......

하지만 불현듯 스치는 한 가지 생각


이런... 그동안 tomcat서버 설정을 ms949에서 utf-8로 바꿨구만...

그래서 파일 encoding이 ms949에서 utf-8로 만들어진거구나... ㅜ.ㅜ


<전달에 성공한 파일 - encoding ascii>


<이번달 생성파일 - utf-8 encoding>


처음으로 시도는 DB에서 데이터 가져와서 파일을 만들때 ascii 형식으로 만들고 값을 저장하면 되겠거니 했는데...

실패~!!!

몬가 미묘한 문제가... DB값도 가져왔을때 이미 utf-8형태이니 이거 변환할때 또 미묘...


그래서 결국은 utf-8 형태로 파일을 만들고 이 파일을 ms949형태로 변환해서 저장하는 것!

다행히 인터넷에 좋은 분 글을 찾고해서 했더니 다행히 변환 성공!


전송도 아주 성공적으로 이뤄졌다.


부끄럽지만 전체소스 공개! (다른 분한테 도움이 되길)

(물론 인터넷 좋은 분 소스를 90% 차용했지만... -.-;)


public class FileCharsetUtil {

	private static final Logger log = LoggerFactory.getLogger(FileCharsetUtil.class);
	
	/**
	 * UTF-8 encoding 파일을 MS949 encoding 파일로 변경
	 * @param inFileName UTF-8 파일 존재위치
	 * @param outFileName 새로 생성될 MS949 파일 저장위치
	 * @throws Exception 
	 */
	public static void convertUTF8toMS949(String inFileName, String outFileName) throws Exception {
		
		// ================================
		FileInputStream fileInputStream = null;
		Reader reader = null;
		Writer writer = null;
		StringBuffer stringBuffer = new StringBuffer();
		
		int intRead = 0;
		log.info("######## convertUTF8toMS949() 처리 시작! {} -> {}", inFileName, outFileName);
		
		fileInputStream = new FileInputStream(inFileName);
		Charset inputCharset = Charset.forName("utf-8");
		InputStreamReader isr = new InputStreamReader(fileInputStream, inputCharset);
		
		reader = new BufferedReader(isr);
		
		while( ( intRead = reader.read() ) > -1 ) {
			stringBuffer.append((char)intRead);
		}
		reader.close();
		
		// 
		FileOutputStream fos = new FileOutputStream(outFileName);
		writer = new OutputStreamWriter(fos, "MS949");
		writer.write(stringBuffer.toString());
		stringBuffer.setLength(0);
		writer.close();
		
		log.info("######## convertUTF8toMS949() 처리 완료!");
	}
}