Infinite Loop when looping through FileInputStream

Alright, so I am writing a Java application to import a csv file and then loop through the results, and load them into an array. I am importing the file correctly because it doesn't through an Exception. My issues is that when I try to count the number of records in the FileInputStream I am trapped in an infinite loop. What could be the issue here. Heres the code:

This is my class with a Main method which calls go():

public void go() {
    pop = new PopularNames();
    popGui = new PopularNamesGui();
    String file = popGui.userInput("Enter the correct name of a file:");
    pop.setInputStream(file);
    pop.getNumberOfNames();
}

This is the class PopularNames (pop), and in the below method I am setting the inputStream var to a new FileINputStream. The file name is provided by the user.

public void setInputStream(String aInputStream) {
    try {
        inputStream = new Scanner(new FileInputStream(aInputStream));
    } catch (FileNotFoundException e) {
        System.out.println("The file was not found.");
        System.exit(0);
    }
}

This is the trouble method. Where I am simply looping through the FileInputStream and counting the number of records:

public void getNumberOfNames() {
    while (this.inputStream.hasNext()) {
        fileDataRows++;
    }
}

Upvotes: 1

Views: 2965

Answers (1)

Prince John Wesley
Prince John Wesley

Reputation: 63688

public void getNumberOfNames() {   
  while (this.inputStream.hasNext()) {   
     inputStream.nextLine(); // Need to read it so that we can go to next line if any
     fileDataRows++;    
  } 
}

Upvotes: 7

Related Questions