Comp Sci Java: Reading a file into an array

Click For Summary
To read a file line by line into an array without using ArrayList in Java, the Scanner class can be utilized with its nextLine() method. The initial code provided had an infinite loop because it did not read the next line within the while loop. Instead, a for loop can be used to iterate through the array, but care must be taken to ensure the array size is sufficient for the number of lines in the file. If the array is too small, it will not capture all lines, suggesting a dynamic approach may be more effective. Ultimately, using Scanner with proper line reading will allow for successful file input into an array.
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 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 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 1 ·
Replies
1
Views
1K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 8 ·
Replies
8
Views
10K
  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
1
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K