我正在写一个函数,它应该检测使用的字符集,然后将其切换到utf-8。我正在使用juniversalchardet,它是mozilla的universalchardet的java端口。
这是我的代码:在java中更改编码
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;
}
}
我的问题是,当我阅读例如波兰的字母,如L,A,C和similiar字母替换的字符文件?和其他奇怪的事情。我究竟做错了什么?编辑: 编辑我使用eclipse。
方法参数是读取MultipartFile的结果。只需使用FileInputStream获取每一行,然后通过某个分隔符分割everyline(它已为xls,xlsx和csv文件准备好)。没有什么特别的。
你是如何编译你的代码的? Eclipse?命令提示符 ?蚂蚁? Maven? – VirtualTroll
一旦你在'字符串'中输入了字符,它们就已经是字符,而不是字节。 – gaborsch
“输入”的来源是什么?请为此显示您的代码。 – gaborsch