Java: Reading a file into an array

Click For Summary

Discussion Overview

The discussion revolves around reading a file line by line into an array using the Scanner class in Java, specifically focusing on the differences between using Scanner and BufferedReader. Participants explore coding techniques and address issues in the provided code snippets.

Discussion Character

  • Homework-related
  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant seeks to understand how to read a file line by line into an array using Scanner, contrasting it with their experience using BufferedReader.
  • Some participants note that the initial code does not read subsequent lines within the while loop, leading to an infinite loop.
  • There is a suggestion to replace the index 0 with the loop variable i to correctly store lines in the array.
  • Another participant points out that the Scanner's hasNextLine() method only checks for the presence of another line without reading it, which is a source of confusion.
  • One participant provides a working example using BufferedReader and suggests a simpler approach without nested loops for reading lines into the array.
  • Another participant confirms that the nextLine() method in Scanner should be used to read the next line, and they share their revised code that successfully reads lines into the array.

Areas of Agreement / Disagreement

Participants generally agree on the need to correctly read lines into the array and the importance of using the nextLine() method. However, there is no consensus on the best approach, as different coding styles and methods are discussed.

Contextual Notes

Some participants express uncertainty about the necessity of certain loops in their code, and there are unresolved questions about the differences in exception handling between Scanner and BufferedReader.

Robben
Messages
166
Reaction score
2

Homework Statement



How do I read in a file line by line into an array without using arraylist?

Homework Equations



None

The Attempt at a Solution



I know how to do this using BufferedReader, but I am wondering how to do this using Scanner? When I used BufferedReader I noticed that there must be two exceptions to be caught which were IOException and FileNotFoundException. Whereas a Scanner needs only a FileNotFoundException, why is that?

Java:
public class practice {
    public String[] array;
    Scanner inputStream = null;
    Scanner n = new Scanner(System.in);  
    public String line;
  
    public practice(String theFile) {       
        array = new String[150];
        try {          
            inputStream = new Scanner(new FileInputStream(theFile));
            line = inputStream.nextLine();

            while (inputStream.hasNextLine()) {
                for (int i = 1; i < array.length; i++){
                    array[0] = line;
                    //dont know what to put here          
                 }
             }            
         } catch(FileNotFoundException e) {
             System.out.println(e.getMessage());
         }
         inputStream.close();    
    }
}
 
Last edited:
Physics news on Phys.org
Some notes on your code:

You're not reading in the next line in your while loop. Since it never reads the second line, it won't ever get out of the loop.
Robben said:
array[0] = line;
You probably want to use i instead of 0 here.
 
Borg said:
Some notes on your code:

You're not reading in the next line in your while loop. Since it never reads the second line, it won't ever get out of the loop.

You probably want to use i instead of 0 here.
But even if I do array = line it still won't take in any lines into the array.
 
Note that when we put i inside of brackets [] outside of a code block, the forum's software is treating that as a marker to turn the rest of the post into italics.
Robben said:
But even if I do array = line it still won't take in any lines into the array.

Before your while loop, you have this code that reads in the first line of the file:
line = inputStream.nextLine();
This reads the first line of the file and assigns it to the variable 'line'.

Your while loop uses inputStream.hasNextLine() to see if there is another line available. However, that doesn't read in the next line from the file. It just looks ahead to see if something is there. So your code just sits at the end of the first line that you read and continually checks to see if the second line is there. This is a classic endless loop error where the code will never exit the while condition. You need to read in the next line and assign it to the variable 'line' like you did the first time.
 
  • Like
Likes   Reactions: Robben
Borg said:
Note that when we put i inside of brackets [] outside of a code block, the forum's software is treating that as a marker to turn the rest of the post into italics.Before your while loop, you have this code that reads in the first line of the file:

This reads the first line of the file and assigns it to the variable 'line'.

Your while loop uses inputStream.hasNextLine() to see if there is another line available. However, that doesn't read in the next line from the file. It just looks ahead to see if something is there. So your code just sits at the end of the first line that you read and continually checks to see if the second line is there. This is a classic endless loop error where the code will never exit the while condition. You need to read in the next line and assign it to the variable 'line' like you did the first time.

Here is my BufferedReader which works fine:

Java:
br = new BufferedReader(new FileReader(fileName));
line = br.readLine();

while ((strLine = br.readLine()) != null) {
    for (int i = 1; i < array.length; i++){
        array[0] = line;
        array[i] = br.readLine();
    }
}
.

But the problem I have with scanner is I am not sure how to go to the next line. In BufferedReader we have readLine(), but I am not sure what to do with scanner.
 
Robben said:
Here is my BufferedReader which works fine:

Java:
br = new BufferedReader(new FileReader(fileName));
line = br.readLine();

while ((strLine = br.readLine()) != null) {
    for (int i = 1; i < array.length; i++){
        array[0] = line;
        array[i] = br.readLine();
    }
}
.

But the problem I have with scanner is I am not sure how to go to the next line. In BufferedReader we have readLine(), but I am not sure what to do with scanner.
There's the nextLine() method in the Scanner class. That should work for you. See http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html and on the same page, http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine().

Regarding your code above, there's a lot of extra motion that isn't needed. For instance, you have a for loop nested inside your while loop. I don't see any need for the for loop. I think the following would work.

Java:
br = new BufferedReader(new FileReader(fileName));
i = 0;
while ((strLine = br.readLine()) != null) {
       array[i++] = strLine;
}

The basic idea is this:
Read a line, and store it in strLine.
If the line read was an empty string, exit the loop.
Otherwise, if the line read wasn't an empty string, store it at the i-th index of array, and then increment i, and then start the loop again.
 
Robben said:

Homework Statement



How do I read in a file line by line into an array without using arraylist?

Homework Equations



None

The Attempt at a Solution



I know how to do this using BufferedReader, but I am wondering how to do this using Scanner? When I used BufferedReader I noticed that there must be two exceptions to be caught which were IOException and FileNotFoundException. Whereas a Scanner needs only a FileNotFoundException, why is that?

Java:
public class practice {
    public String[] array;
    Scanner inputStream = null;
    Scanner n = new Scanner(System.in);
    public String line;

    public practice(String theFile) {    
        array = new String[150];
        try {       
            inputStream = new Scanner(new FileInputStream(theFile));
            line = inputStream.nextLine();

            while (inputStream.hasNextLine()) {
                for (int i = 1; i < array.length; i++){
                    array[0] = line;
                    //dont know what to put here       
                 }
             }         
         } catch(FileNotFoundException e) {
             System.out.println(e.getMessage());
         }
         inputStream.close(); 
    }
}
Mark44 said:
There's the nextLine() method in the Scanner class. That should work for you. See http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html and on the same page, http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine().

Regarding your code above, there's a lot of extra motion that isn't needed. For instance, you have a for loop nested inside your while loop. I don't see any need for the for loop. I think the following would work.

Java:
br = new BufferedReader(new FileReader(fileName));
i = 0;
while ((strLine = br.readLine()) != null) {
       array[i++] = strLine;
}

The basic idea is this:
Read a line, and store it in strLine.
If the line read was an empty string, exit the loop.
Otherwise, if the line read wasn't an empty string, store it at the i-th index of array, and then increment i, and then start the loop again.

I see, thank you very much! I also just got it to work by taking out the while loop and only using the foor loop. My code now looks like this:

Java:
try {          
    inputStream =
        new Scanner(new FileReader(fileName));
    line = inputStream.nextLine();  
 
    for (int i = 0; i < array.length; i++) {
        array[i] = inputStream.nextLine();  
    }
    
    inputStream.close();     
     } catch(FileNotFoundException e) {
       System.out.println(e.getMessage());
     }
 
Robben said:
I see, thank you very much! I also just got it to work by taking out the while loop and only using the foor loop. My code now looks like this:

Java:
try {         
    inputStream =
        new Scanner(new FileReader(fileName));
    line = inputStream.nextLine(); 

    for (int i = 0; i < array.length; i++) {
        array[i] = inputStream.nextLine(); 
    }
   
    inputStream.close();    
     } catch(FileNotFoundException e) {
       System.out.println(e.getMessage());
     }
The problem with this approach is that if your array is declared too small, your loop will end before all the lines are read from the input file. That's also a problem in the code I gave, so you need to make sure that you have some idea how big the input file is at compile time. One workaround is to use dynamic arrays, arrays that can be resized at run-time.
 
Mark44 said:
The problem with this approach is that if your array is declared too small, your loop will end before all the lines are read from the input file. That's also a problem in the code I gave, so you need to make sure that you have some idea how big the input file is at compile time. One workaround is to use dynamic arrays, arrays that can be resized at run-time.

I see, in that case I should use arrayList?
 
  • #10
Robben said:
I see, in that case I should use arrayList?
Might be a good idea.
 
  • Like
Likes   Reactions: Robben
  • #11
Here's a way to do this using the java.nio.file.Files.readAllLines() method which returns a list of Strings as lines of the file. I'm showing 2 ways to do this:

1) reading in the file contents into a list of Strings and
2) reading in the file contents into a list of String and then creating an array of Strings based on the size of the List and populating that array with the List of String

This is part of a much larger article about how to read files in Java.

Solution 1:
Java:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    List  fileLinesList = Files.readAllLines(file.toPath());

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}

Solution 2:
Java:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines {
    public static void main(String [] pArgs) throws IOException {
        String fileName = "c:\\temp\\2.sample-10KB.txt";
        File file = new File(fileName);

        List <String> fileLinesList = Files.readAllLines(file.toPath());
        String [] fileLines = new String[fileLinesList.size()];
        int i=0;
        for(String line : fileLinesList) {
            fileLines[i++] = line;
        }
       
        for(int j=0; j<fileLines.length; j++) {
            System.out.println("fileLines[" + j + "]=" + fileLines[j]);
        }
    }
}
 

Similar threads

  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 8 ·
Replies
8
Views
10K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 12 ·
Replies
12
Views
2K
Replies
1
Views
2K