How to read data with different separators?

后端 未结 3 1362
夕颜
夕颜 2020-12-14 12:03

I have a file looks like:

a 1,2,3,5
b 4,5,6,7
c 5,6,7,8
...

That the separator between 1st and 2nd is \'\\t\', other separators are comma.

3条回答
  •  轮回少年
    2020-12-14 12:48

    Scanner scan = new Scanner(file);
    while (scan.hasNextLine()) {
        String[] a = scan.nextLine().replace("\\t", ",").split(",");
        //do something with the array
    }
    scan.close();
    

    This did:

    1. create a scanner to process the file (Scanner scan)
    2. scan in the next file line (scan.nextLine()) for each file line based on hasNextLine()
    3. replaced tabs with commas (.replace("\t", ",")), so the separators were all the same
    4. split into an array by commas. Now you can process all the data alike regardless of the length of each line.
    5. Don't forget to close the scanner when you're done.

提交回复
热议问题