简体   繁体   English

OpenCSV解析不显示特殊字符

[英]OpenCSV parsing does not show special character

I am trying to load a .csv file in jTable. 我正在尝试在jTable中加载.csv文件。 In notepad the file shows OK but in jTable some characters like "£", "$" becomes a box. 在记事本中,文件显示OK,但在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);
    }
}

How can I solve this problem ? 我怎么解决这个问题 ?

Match the encoding of your file to that used by the InputStreamReader , for example if your file is ISO-8859-1, you can use 将文件的编码与InputStreamReader使用的编码匹配,例如,如果您的文件是ISO-8859-1,则可以使用

CSVReader reader = new CSVReader(
        new InputStreamReader(new FileInputStream(filename), "ISO-8859-1")); 

UTF-8 requires 2 bytes to display a character whereas ISO-8859-1 only required 1. If an ISO-8859-1 encoded file is read using UTF-8, then characters such as £ will not display correctly if displayed with the latter. UTF-8需要2个字节才能显示字符,而ISO-8859-1只需要1.如果使用UTF-8读取ISO-8859-1编码文件,那么如果用后者显示,则£等字符将无法正确显示。

Read: A Rough Guide to Character Encoding 阅读: 字符编码的粗略指南

You need to specify the encoding of the file you want to read. 您需要指定要读取的文件的编码。

try new InputStreamReader(new FileInputStream(...), <encoding>) , or something like this instead of new FileReader(filename) 尝试new InputStreamReader(new FileInputStream(...), <encoding>) ,或类似的东西,而不是new FileReader(filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM