2013-09-27 112 views
3

我想在jTable中加載一個.csv文件。在記事本中,文件顯示OK,但在jTable中有一些字符,如「£」,「$」變成了一個盒子。OpenCSV解析不顯示特殊字符

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); 
    } 
} 

我該如何解決這個問題?

+0

永遠,永遠,使用類「的FileReader」 – AgilePro

回答

3

匹配您的文件,由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

+0

您的文件可能有不同的編碼,與ISO-8859-1嘗試。請參閱更新 – Reimeus

+0

ISO-8859-1正常工作。 「UTF-8」沒有。但原因還不得而知。無論如何,謝謝Reimeus。 –

+0

已添加說明... – Reimeus

0

您需要指定要讀取文件的編碼。

嘗試new InputStreamReader(new FileInputStream(...), <encoding>),或這樣的事情,而不是new FileReader(filename)