Search code examples
javalistsplitstreamreadfile

Reading only numbers from text file and splitting comma to List


Want to read numbers from a file and add them to List<Integer>. But the problem happens to be that two-digit numbers are also split into 2 separate numbers when reading the file.

Text file example:

2, 7
1, 0, 24, 2
3, 0, 6, 3
4, 0, 2, 1

My code:

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ReadFile {

    public void readTestCase(String files) throws IOException {

        File file = new File(files);
        byte[] bytes = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(bytes);
        fis.close();
        String[] valueStr = new String(bytes).trim().split("");
        List<Integer> arr = new ArrayList<>();

        for (int i = 0; i < valueStr.length; i++) {
            if(isNumeric(valueStr[i])) {
                arr.add(Integer.parseInt(valueStr[i]));
            }
        }

        System.out.println(arr);

    }

    public static boolean isNumeric(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch(NumberFormatException e){
            return false;
        }
    }

}

This code output: [2, 7, 1, 0, 2, 4, 2, 3, 0, 6, 3, 4, 0, 2, 1]

The correct output should be: [2, 7, 1, 0, 24, 2, 3, 0, 6, 3, 4, 0, 2, 1]

Now, this code works but the problem is in the text file number "24" is also split into "2" and "4". So my file should contain only 14 numbers in the list. Now it has 15 numbers. I also try to modify split like this .split(",");, .split(", "); and the output is always wrong.

Thanks in advance.


Solution

  • You can split the string on non-digit characters "\\D+" (one or more non-digit characters):

    new String(bytes).trim().split("\\D+");