Java: Reading a file into an array

In summary: Read MoreIn summary, the conversation discusses how to read in a file line by line into an array without using ArrayList. The attempt includes code using BufferedReader and Scanner, and the main issue is understanding how to go to the next line when using Scanner. Suggestions are made to use the nextLine() method in the Scanner class.
  • #1
Robben
166
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
  • #2
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.
 
  • #3
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.
 
  • #4
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
  • #5
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.
 
  • #6
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.
 
  • #7
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());
     }
 
  • #8
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.
 
  • #9
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]);
        }
    }
}
 

1. How do I read a file into an array using Java?

To read a file into an array in Java, you can use the BufferedReader class from the java.io package. First, you need to create a BufferedReader object and pass in a FileReader object which takes the file path as a parameter. Then, you can use the readLine() method to read each line of the file and store it in an array.

2. What is the benefit of reading a file into an array?

Reading a file into an array allows for easier manipulation and access to the data within the file. Instead of having to read the file line by line every time, storing the data in an array allows for faster and more efficient processing.

3. How can I handle errors while reading a file into an array?

You can use try-catch blocks to handle any potential errors while reading a file into an array. For example, if the file path is incorrect or the file does not exist, an IOException will be thrown. By using try-catch, you can catch this exception and handle it accordingly.

4. Can I read different types of data into an array using Java?

Yes, you can read different types of data into an array using Java. The BufferedReader class has methods like readInt(), readDouble(), and readBoolean() that allow you to read specific types of data from the file and store them in an array.

5. Is there a limit to the size of the file that can be read into an array using Java?

There is no specific limit to the size of the file that can be read into an array using Java. However, it is important to consider the available memory and resources of your system. Reading a very large file into an array may cause memory issues and affect the performance of your program.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
11
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
18
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
941
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
6
Views
2K
  • Programming and Computer Science
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
9K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
Back
Top