Java - Splitting a CSV file into an Array

前端 未结 4 1558
别跟我提以往
别跟我提以往 2021-01-19 14:38

I have managed to split a CSV file based on the commas. I did this by placing a dummy String where ever there was a \',\' and then splitting based on the dummy String.

相关标签:
4条回答
  • 2021-01-19 15:12

    I don't see why you need a dummy string. Why not split on comma?

    BufferedReader in = new BufferedReader(new FileReader("file.csv"));
    String line;
    while ((line = in.readLine()) != null) {
        String[] fields = line.split(",");
    }
    
    0 讨论(0)
  • 2021-01-19 15:18

    As per the dummy strings you mentioned, it could be easily processed with the help of an existing library. I would like to recommand the open source library uniVocity-parsers, which procides simplfied API, significent performance and flexibility.

    Just refer to few lines of code to read csv data into memory with array:

    private static void parseCSV() throws FileNotFoundException {
        CsvParser parser = new CsvParser(new CsvParserSettings());
        List<String[]> parsedData = parser.parseAll(new FileReader("/examples/example.csv"));
    
        for (String[] row : parsedData) {
            StringBuilder strBuilder = new StringBuilder();
            for (String col : row) {
                strBuilder.append(col).append("\t");
            }
            System.out.println(strBuilder);
        }
    }
    
    0 讨论(0)
  • 2021-01-19 15:23

    I would strongly recommend you not reinventing the wheel :). Go with one of the already available libraries for handling CSV files, eg: OpenCSV

    0 讨论(0)
  • 2021-01-19 15:30

    use the followin it will split lines

                   String[] a=scanner.next().split(" ");
    
    0 讨论(0)
提交回复
热议问题