我正在尝试在 jTable 中加载一个 .csv 文件。在记事本中,文件显示正常,但在 jTable 中,一些字符如“£”、“$”变成了一个框。
private void parseUsingOpenCSV(String filename){
DefaultTableModel model = (DefaultTableModel) empTbl.getModel();
int rows = model.getRowCount();
if (rows>0){
for(int i=0 ; i<rows; i++)
{model.removeRow(0);}
}
try {
CSVReader reader = new CSVReader(new FileReader(filename));
String [] nextLine;
int rowNumber = 0;
while ((nextLine = reader.readNext()) != null) {
rowNumber++;
model.addRow(new Object[]{nextLine[0], nextLine[1], nextLine[2], nextLine[3], nextLine[4], nextLine[5], nextLine[6], nextLine[7]});
}
} catch (IOException e) {
System.out.println(e);
}
}
我该如何解决这个问题?
最佳答案
将您的文件编码与 InputStreamReader
使用的编码相匹配,例如,如果您的文件是 ISO-8859-1,您可以使用
CSVReader reader = new CSVReader(
new InputStreamReader(new FileInputStream(filename), "ISO-8859-1"));
UTF-8 需要 2 个字节来显示一个字符,而 ISO-8859-1 只需要 1 个。如果使用 UTF-8 读取 ISO-8859-1 编码的文件,则字符如 £
如果用后者显示将无法正确显示。
关于java - OpenCSV 解析不显示特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19048114/