2013-02-15 457 views
2

我在包含多行的文件中有csv。如果第一列的值沒有任何錯誤,並且m不能在數據庫中插入。 ex 如果行是:130,1,datafile8.csv,2007,17,List_date在讀取n時沒有問題插入 但是如果行是:,0,datafile8.csv,Bihar,7,list_Left,無法讀取n插入。如何在上面的行中插入null。因此,我可以在數據庫中插入dis行。java代碼如何讀取csv文件中的空值

String keyword = "celldescription.csv"; 
File makefile = new File(keyword); 
    BufferedReader r2 = new BufferedReader(new FileReader(makefile)); 
    strLine1 = r2.readLine(); 
    System.out.println (strLine1); 
    String r="0";int r1=0; 

    while((strLine1=r2.readLine())!=null) 
    { 
    System.out.println (strLine1); 

    StringTokenizer st2 = new StringTokenizer(strLine1, ","); 
    // Print the content on the console 


     String cellvalue = st2.nextToken();   


     String position = st2.nextToken(); 


     String Docid=st2.nextToken(); 


     String Word=st2.nextToken(); 


     String Count=st2.nextToken(); 

     String List_Entry=st2.nextToken(); 


     String tab3="insert into description(cellvalue,position,Docid,Word,Count,List_Entry) values(?,?,?,?,?,?)"; 
     ps = connection.prepareStatement(tab3); 
     ps.setString (1,cellvalue); 
     ps.setString (2,position); 
     ps.setString (3,Docid); 
     ps.setString (4,Word); 
     ps.setString (5,Count); 
     ps.setString (6,List_Entry); 
     ps.executeUpdate(); 



}//end of while 



    r2.close(); 

System.out.println("Data is inserted"); 

     }//try closed** 
+3

我還沒有在代碼中看到'StringTokenizer'很長一段時間。你可能要考慮使用'String.split(「,」)'代替。 – Perception 2013-02-15 10:09:24

+0

添加空檢查很困難嗎?嗯.. – StarPinkER 2013-02-15 10:10:04

+1

此外,CSV看起來相當複雜(引用的值包括分隔符等)。我建議使用第三方API,Apache有一個看起來不錯的。 – SJuan76 2013-02-15 10:10:52

回答

2

當你String strLine1開始用逗號(,)StringTokenizer忽略空字符串,如果是在開始或結束,甚至在兩者之間。

防爆 - ,0,datafile8.csv,Bihar,7,list_Left

令牌 - >"0" - "datafile8.csv" - "Bihar" - "7" and "list_Left"

更好您可以通過逗號分割字符串(,)。 防爆 -

String[] str = strLine1.split(",",-1); 

STR [1] - >["","datafile8.csv","Bihar","7" and "list_Left"]

1

您可能需要考慮使用Java庫使用CSV文件,你的工作。 OpenCSV是一個,它幫助了我很多。

它的一些特性:

  • 每行
  • 忽略逗號值的任意號碼引述元素
  • 處理引述具有嵌入回車條目(即跨越多行的條目)
  • 可配置的分隔符和引號字符(或使用合理的默認值)
  • 一次讀取所有條目,或使用迭代器樣式模型
  • 從String []創建csv文件(即。嵌入式引用字符的自動轉義)