我的文件中有包含多行的 csv。如果第一列值什么都没有,则会出现错误,并且无法插入数据库。 前任 如果行是 :130,1,datafile8.csv, 2007 ,17,List_date 读取 n 插入没有问题 但如果行是:,0,datafile8.csv,Bihar,7,list_Left,无法读取n插入。如何在上面的行中插入null。这样我就可以在数据库中插入dis行。
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**
最佳答案
当您的 String strLine1
以逗号(,) 开头时,StringTokenizer
忽略空字符串(如果它位于开头或结尾,甚至位于两者之间)。
例如 - ,0,datafile8.csv,比哈尔邦,7,list_Left
token -> “0” - “datafile8.csv” - “比哈尔邦” - “7”和“list_Left”
最好用逗号(,)分割字符串。 前-
String[] str = strLine1.split(",",-1);
str[] -> [“”、“datafile8.csv”、“比哈尔邦”、“7”和“list_Left”]
关于java代码如何读取csv文件中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14892291/