Search code examples
javafilereader

Java; Writing int from characters in file to an array


I need to convert a file into an int array, my source have a strict formatting. Each single character correspond a int(or byte) to be stored in an array, spacing delimiting a new array in a 2D Array.

The file would be formatted as so. (x,y,z coordinates), each character of a 3 number string needing to be stored individually.

013 234 456 567

My desired output would be as so.

{0,1,3}{2,3,4}{4,5,6}{5,6,7}

Would there be achieve directly from a file reading method or will I have to import them as string with a scanner, than separate the numbers from there?


Solution

  • Try this:

    int[][][] array = Files.lines(Path.of("myfilename.txt"))
        .map(line -> Arrays.stream(line.split(" ")) // split line into terms
                .map(term -> term.chars().map(Character::getNumericValue).toArray()) // convert each term to int[]
                .toArray(int[][]::new)) // convert each line to int[][]
        .toArray(int[][][]::new); // convert all lines of file to a single int[][][]
    

    See live demo.