Parsing CSV in java

后端 未结 9 1871
臣服心动
臣服心动 2020-11-27 21:12

I have this weird situation where I have to read horizontally. So I am getting a csv file which has data in horizontal format. Like below:

CompanyName,RunDat         


        
9条回答
  •  伪装坚强ぢ
    2020-11-27 21:44

    java.time

    Assuming you are using a CSV library for reading the file and supposing that you get the individual values as strings from that library:

        String valueFromCsvLibrary = "10/27/2010";
        try {
            LocalDate date = LocalDate.parse(valueFromCsvLibrary, dateFormatter);
            System.out.println("Parsed date: " + date);
        } catch (DateTimeParseException dtpe) {
            System.err.println("Not a valid date: " + dtpe);
        }
    
    Parsed date: 2010-10-27
    

    You should prefer to process the dates as LocalDate in your code (neither as strings nor as instances of the long outdated and poorly designed Date class).

    Even though I don’t have the experience, I am quite convinced that I would go with some open source CSV library.

    Only in case you are sure that the CSV file doesn’t contain quotes, broken lines, commas in the values or other complications and for some reason you choose to parse it by hand:

        String lineFromCsvFile = "CompanyName,RunDate,10/27/2010,11/12/2010,11/27/2010,12/13/2010,12/27/2010";
        String[] values = lineFromCsvFile.split(",");
        if (values[1].equals("RunDate")) {
            for (int i = 2; i < values.length; i++) {
                LocalDate date = LocalDate.parse(values[i], dateFormatter);
                System.out.println("Parsed date: " + date);
            }
        }
    
    Parsed date: 2010-10-27
    Parsed date: 2010-11-12
    Parsed date: 2010-11-27
    Parsed date: 2010-12-13
    Parsed date: 2010-12-27
    

    Exception handling happens as before, no need to repeat that.

提交回复
热议问题