Get Column and Row Size of File Java

Viewed 22

i want to get the file column length and row length.

    public static void main(String[] args) throws Exception {
    InputStream is = GameBoard.class.getClassLoader().getResourceAsStream("level1.txt");
    String result = IOUtils.toString(is, StandardCharsets.UTF_8);
    System.out.println(result);
    }

The file has 10 columns and 10 rows. I now want to save this number in a variable. However, I have read out the file with "Apache Commons IO" and therefore cannot find much about it on the internet. I would be glad if someone could help me.

1 Answers

Solution:

        InputStream is = GameBoard.class.getClassLoader().getResourceAsStream("level1.txt");
    String result = IOUtils.toString(is, StandardCharsets.UTF_8);
    char column;
    int totalColumns = 0;
    for (int i = 0; i < result.length(); i++) {
        column = result.charAt(i);
        if (column == '\n') {
            totalColumns++;
        }
    }
    int totalRows = 0;
    char occ = '\n';
    for(int i=0; i < result.length(); i++)
    {    if(result.charAt(i) == occ)
        totalRows++;
    }
    System.out.println(totalColumns);
    System.out.println(totalRows);
Related