【问题标题】:skipping a file from a csv file based on the parameter根据参数从 csv 文件中跳过文件
【发布时间】:2013-10-30 14:05:35
【问题描述】:

我有一个 csv 文件。我正在将其上传到 MySQL。上传时,我必须检查每一行中是否存在所有值。 例如:

    File A has
    aaa, bbb, ccc, ddd (line 1)
    eee, fff, ggg, hhh (line 2)
    iii, jjj, kkk (line 3)
    jjj, kkk, lll, mmm (line 4 )

在上面的文件中,第 3 行只有 3 个值。要求是第三行必须写在单独的文件中。其他三行必须更新表格。

它应该跳过第 3 行并且必须写入单独的文件。

有什么帮助吗?

【问题讨论】:

  • 你是如何将文件“上传”到mysql的?
  • 用 ',' 分割文件,如果长度小于所需数字(本例中为 4),则不要写入 MySQL。

标签: java filehandle


【解决方案1】:
String csvFile = "file.csv";
String line;

BufferedReader br = new BufferedReader(new FileReader(csvFile)); 

while((line = br.readLine()) != null) {

    String[] country = line.split(",");
    if(country.length == 4) {
        //Do whatever should be done
    } 
}

这是基于http://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/中的示例1

你当然应该做任何你需要修改存在的元素的数量

【讨论】:

  • 顺便说一句,您在检查期间是否还需要它来写入新文件?
【解决方案2】:

你可以用这样的东西,

while ((line = bufRdr.readLine()) != null) {

           StringTokenizer st = new StringTokenizer(line, delims);
           int length = st.countTokens();
           System.out.println("len " + st.countTokens());
           if (length != 4) {
               continue;
           }
           writer.write(line);// you can save all the lines with 4 words into another csv file

       }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多