【问题标题】:OpenCSV parsing does not show special characterOpenCSV 解析不显示特殊字符
【发布时间】:2013-09-27 10:07:45
【问题描述】:

我正在尝试在 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);
    }
}

我该如何解决这个问题?

【问题讨论】:

  • 永远不要使用“FileReader”类

标签: java swing jtable opencsv


【解决方案1】:

将您的文件编码与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 编码文件,则 £ 等字符将无法正确显示如果与后者一起显示。

阅读:A Rough Guide to Character Encoding

【讨论】:

  • 您的文件可能有不同的编码,请尝试使用 ISO-8859-1。查看更新
  • ISO-8859-1 工作正常。 “UTF-8”没有。但原因仍然未知。无论如何,谢谢 Reimeus。
猜你喜欢
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多