csv解析器读取标头

时间:2012-06-26 15:55:39

标签: java parsing csv

我正在开发一个csv解析器,我想分别读取头文件和其余的csv文件。 这是我读取csv的代码。

当前代码读取csv文件中的所有内容,但我需要单独读取标头。 请帮我解决这个问题。

public class csv {

private void csvRead(File file)
{
    try
    {
    BufferedReader br = new BufferedReader( new FileReader(file));
    String strLine = "";
    StringTokenizer st = null;
    File cfile=new File("csv.txt");
    BufferedWriter writer = new BufferedWriter(new FileWriter(cfile));
    int tokenNumber = 0;

    while( (strLine = br.readLine()) != null)
    {
            st = new StringTokenizer(strLine, ",");
            while(st.hasMoreTokens())
            {

                    tokenNumber++;
                    writer.write(tokenNumber+"  "+ st.nextToken());
                    writer.newLine();
            }


            tokenNumber = 0;
            writer.flush();
    }
}

    catch(Exception e)
    {
        e.getMessage();
    }
}

3 个答案:

答案 0 :(得分:6)

请考虑使用Commons CSV。该库是根据RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files编写的。阅读这些内容的兼容性是什么:

"aa,a","b""bb","ccc"

使用非常简单,只有3个类,并且根据文档提供了一些小样本:

  

解析具有制表符作为分隔符的csv-string,'“作为可选项   值封装器和以“#”开头的注释:

 CSVFormat format = new CSVFormat('\t', '"', '#');
 Reader in = new StringReader("a\tb\nc\td");
 String[][] records = new CSVParser(in, format).getRecords();

此外,您还可以将此解析器作为常量使用:

  • DEFAULT - RFC 4180定义的标准逗号分隔格式。
  • EXCEL - Excel文件格式(使用逗号作为值分隔符)。
  • MYSQL - SELECT INTO OUTFILE和LOAD DATA INFILE操作使用的默认MySQL格式。 TDF - 制表分隔格式。

答案 1 :(得分:6)

我们在CSVFormat中提供了withHeader()方法。如果使用此选项,则可以使用标题读取文件。

CSVFormat format = CSVFormat.newFormat(',').withHeader();
Map<String, Integer> headerMap = dataCSVParser.getHeaderMap(); 

将为您提供所有标题。

public class CSVFileReaderEx {
    public static void main(String[] args){
        readFile();
    }

    public static void readFile(){
         List<Map<String, String>> csvInputList = new CopyOnWriteArrayList<>();
         List<Map<String, Integer>> headerList = new CopyOnWriteArrayList<>();

         String fileName = "C:/test.csv";
         CSVFormat format = CSVFormat.newFormat(',').withHeader();

          try (BufferedReader inputReader = new BufferedReader(new FileReader(new File(fileName)));
                  CSVParser dataCSVParser = new CSVParser(inputReader, format); ) {

             List<CSVRecord> csvRecords = dataCSVParser.getRecords();

             Map<String, Integer> headerMap = dataCSVParser.getHeaderMap();
              headerList.add(headerMap);
              headerList.forEach(System.out::println);

             for(CSVRecord record : csvRecords){
                 Map<String, String> inputMap = new LinkedHashMap<>();

                 for(Map.Entry<String, Integer> header : headerMap.entrySet()){
                     inputMap.put(header.getKey(), record.get(header.getValue()));
                 }

                 if (!inputMap.isEmpty()) {
                     csvInputList.add(inputMap);
                } 
             }

             csvInputList.forEach(System.out::println);

          } catch (Exception e) {
             System.out.println(e);
          }
    }
}

答案 2 :(得分:3)

您考虑过OpenCSV吗?

此前的问题......

CSV API for Java

看起来你可以很容易地拆分标题......

String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));


// if the first line is the header
String[] header = reader.readNext();

// iterate over reader.readNext until it returns null
String[] line = reader.readNext();
相关问题