javabufferedreaderfilereadernetbeans-13

Reading table from a text file to a 2darray


i have a java code where i read a txt file, then iterate it so that i can fill it in a 2d array. after i read the file i was able to print out its contents so i was sure that the file was read. and i was also sure that the bufferedreader library's .hasNextLine method was showing true when a line was found. but when i used it in a while loop, it just acted as if no lines where found, thus it didnt iterate, hense i couldn't know how many rows i had in the table.==>


while (sc.hasNextLine()==true){ row++;}

furthermore, when i hard-coded the number of rows so that i could check if everything else was ok, i got a line not found error. please help me out. i will link the code below.


    package com.company;
    import java.io.BufferedReader;
   import java.io.FileReader;
   import java.util.Arrays;
   import java.util.Scanner;
   public class Main {

        public static void 
    main(String args[]) throws Exception {
        int row=0;
        int column=0;
        int count=0;

        BufferedReader x = new BufferedReader(new FileReader("src\\Table.txt"));
        Scanner sc = new Scanner(x);
        System.out.println(sc.nextLine()+sc.hasNextLine()+"\n"+sc.nextLine()+sc.hasNext()+"\n"+sc.nextLine()+"\n"+sc.nextLine()+sc.hasNextLine());

        while (sc.hasNextLine()==true){ row++;}
        System.out.println(row);
        for (int i=0; i<row; i++) {
            String[] line = sc.nextLine().trim().split(",");
            System.out.println(line);
            for (String line1 : line) {
                if (",".equals(line1)) {
                    count++;
                }
                count+=1;
                if(count>column){
                    column=count;
                }
            }
        }
        String [][] myArray = new String[row][column];


        for (int i=0; i<myArray.length; i++) {
            String[] line = sc.nextLine().trim().split(",");
            for (int j=0; j<line.length; j++) {
                myArray[i][j]= line[j];
            }
        }

        System.out.println(Arrays.deepToString(myArray));
    }
}

i also get this output

"C:\Program Files\Java\jdk-12.0.1\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.3.2\lib\idea_rt.jar=52205:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2021.3.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\acer pc\IdeaProjects\PDM\out\production\PDM" com.company.Main
CalculusII,Algebra,Networktrue
CalculusII,Algebra,Webtrue
CalculusIII,Prog2,Network
Algebra,Prog1,Webfalse
0
[]

Process finished with exit code 0

Solution

  • When you perform the following statement you've already read your entire file, so there are no lines left to read.

    System.out.println(sc.nextLine()+sc.hasNextLine()+"\n"+sc.nextLine()+sc.hasNext()+"\n"+sc.nextLine()+"\n"+sc.nextLine()+sc.hasNextLine());
    

    This is why your following iterations stop immediately and don't show the expected output. Maybe, what you were expecting was for the Scanner's internal cursor to reset itself once the end of file was reached. However, this is definitely not the behavior of the Scanner class (or any other), and none of its methods offer to reset or reposition the Scanner's cursor to a specific point of the file.

    What you need to do is to close your connections and re-establish them in order to restart reading the content. For example, you could include every file consumption within a try block to automatically dispose every connection once you're done.

    To simplify your code, in your first loop you could count the number of lines and check for the line with "the most columns", while in your second loop you could re-read the file's content.

    public class Main {
        public static void main(String args[]) {
            int row = 0;
            int column = 0;
            int tmp = 0;
    
            try (FileReader fr = new FileReader("src\\Table.txt");
                 BufferedReader br = (new BufferedReader(fr));
                 Scanner sc = new Scanner(br)) {
    
                //First file consumption
                while (sc.hasNextLine()) {
                    row++;
                    tmp = sc.nextLine().split(",").length;
                    if (tmp > column) {
                        column = tmp;
                    }
                }
                System.out.println(row);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    
            try (FileReader fr = new FileReader("src\\Table.txt");
                 BufferedReader br = (new BufferedReader(fr));
                 Scanner sc = new Scanner(br)) {
    
                //Second file consumption
                String[][] myArray = new String[row][column];
                for (int i = 0; i < myArray.length; i++) {
                    String[] line = sc.nextLine().trim().split(",");
                    for (int j = 0; j < line.length; j++) {
                        myArray[i][j] = line[j];
                    }
                }
                System.out.println(Arrays.deepToString(myArray));
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }