在读取java中的CSV文件时,空行无法打印

时间:2014-05-13 07:18:46

标签: java csv

我有以下代码,我在java中读取csv文件,csv文件如下

"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"

以下代码用于在java中读取文件

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class CSVFileReader {

  public static void main(String[] args) {

    CSVFileReader obj = new CSVFileReader();
    obj.run();

  }

  public void run() {

    String csvFile = "Whois.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] country = line.split(cvsSplitBy);
                if(line.contains("AU") || line.contains("AU"))
                {

                         System.out.println("Country [code= " + country[4] 
                                 + " , name=" + country[5] + "]");
                }
                else
                {
                        System.out.println("");
                }

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    System.out.println("Done");
  }

}

使用这个java代码我正在读取我在行中获取AU的行。正确显示两个结果是正确的但是我想要在哪里我没有得到AU字符串行。它应该将该行打印为空白。

正如我们在csv文件代码中看到的那样。AU在第一行和第三行,它打印两行,其中AU存在。我希望输出为第一行AU行然后第二行应为空白然后在第三行所需的AU值......

我如何打印第二个空行,现在它打印两行包含AU的行

1 个答案:

答案 0 :(得分:1)

要为非AU线写一个空行,你可以写:

String[] country = line.split(cvsSplitBy);
if( line.contains("AU") ) {
   System.out.println("Country [code= " + country[4]  + " , name=" + country[5] + "]");
} else {
   System.out.println("");
}

虽然这种方法不是一个好的编码/设计的例子(可能除了最简单的单一用途脚本,但它并不重要)。

我建议考虑分离CSV结果的处理(以接收CSV文件的方法的形式并返回已处理的行/结果的集合)并将其打印出来(接收行的集合/结果并迭代打印它们)。

通过这种方式,您可以自动测试已正确处理结果。