gimmickbutreal
[JAVA/ENCODING] 자바로 엑셀 파일 인코딩 변경하기 본문
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
import java.io.*;
public class ConvertToUtf8 {
public static void main(String[] args) {
try {
// 원본 파일 경로 (변경 필요)
String inputFilePath = "C:\\Users\\input.csv";
// UTF-8로 변환된 파일 경로 (변경 필요)
String outputFilePath = "C:\\Users\\output_UTF8.csv";
// 파일을 cp949로 읽기 위해 FileInputStream을 생성
FileInputStream fis = new FileInputStream(inputFilePath);
// 파일을 UTF-8로 쓰기 위해 BufferedWriter를 생성
FileOutputStream fos = new FileOutputStream(outputFilePath);
// BOM을 사용하여 UTF-8로 설정
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write('\ufeff'); // BOM 쓰기
// 버퍼를 사용하여 데이터를 읽고 쓰기
char[] buffer = new char[4096];
int charsRead;
InputStreamReader isr = new InputStreamReader(fis, "cp949");
while ((charsRead = isr.read(buffer)) != -1) {
osw.write(buffer,0,charsRead);
}
// 리소스를 닫음
fis.close();
osw.close();
System.out.println("원본 파일(CP949)이 UTF-8로 변환되었습니다.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
cs |
대다수의 공공데이터가 CP949 형식으로 되어 있기 때문에 범용성 있는 사용을 위해선 UTF-8로의 변환 과정이 필요합니다. 위 코드는 이에 필요한 코드입니다.
본인은 버퍼를 사용해 데이터를 읽고 쓸 때 byte로 하느라 애를 많이 먹었는데 char로 하니까 해결이 되었습니다.
반응형
'Programming' 카테고리의 다른 글
[JAVA/CSV] Java로 csv 파일 데이터 변경하기 (1) | 2023.10.06 |
---|---|
[PostgreSQL] Mac 환경에서 RDS 연동하기 (0) | 2023.08.25 |