使用されている文字セットを検出し、utf-8 に切り替える関数を作成しています。mozillaによるuniversalchardetのJavaポートであるjuniversalchardetを使用しています。
これは私のコードです:
private List<List<String>> setProperEncoding(List<List<String>> input) {
try {
// Detect used charset
UniversalDetector detector = new UniversalDetector(null);
int position = 0;
while ((position < input.size()) & (!detector.isDone())) {
String row = null;
for (String cell : input.get(position)) {
row += cell;
}
byte[] bytes = row.getBytes();
detector.handleData(bytes, 0, bytes.length);
position++;
}
detector.dataEnd();
Charset charset = Charset.forName(detector.getDetectedCharset());
Charset utf8 = Charset.forName("UTF-8");
System.out.println("Detected charset: " + charset);
// rewrite input using proper charset
List<List<String>> newLines = new ArrayList<List<String>>();
for (List<String> row : input) {
List<String> newRow = new ArrayList<String>();
for (String cell : row) {
//newRow.add(new String(cell.getBytes(charset)));
ByteBuffer bb = ByteBuffer.wrap(cell.getBytes(charset));
CharBuffer cb = charset.decode(bb);
bb = utf8.encode(cb);
newRow.add(new String(bb.array()));
}
newLines.add(newRow);
}
return newLines;
} catch (Exception e) {
e.printStackTrace();
return input;
}
}
私の問題は、たとえばポーランド語のアルファベットの文字を含むファイルを読み取ると、ł、ą、ćなどの文字が ? に置き換えられることです。そして他の奇妙なこと。私は何を間違っていますか?
編集:コンパイルにはEclipseを使用しています。
メソッド パラメータは、MultipartFile を読み取った結果です。FileInputStream を使用してすべての行を取得し、すべての行を区切り文字で分割するだけです (xls、xlsx、および csv ファイル用に事前に用意されています)。特別なことは何もありません。