• Support PF! Buy your school textbooks, materials and every day products Here!

Java: Reading a file into an array

  • Comp Sci
  • Thread starter Robben
  • Start date
  • #1
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:

Answers and Replies

  • #2
Borg
Science Advisor
Gold Member
1,871
2,222
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.
array[0] = line;
You probably want to use i instead of 0 here.
 
  • #3
166
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.

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
Borg
Science Advisor
Gold Member
1,871
2,222
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.
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.
 
  • #5
166
2
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
33,173
4,858
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
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(); 
    }
}
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
33,173
4,858
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
166
2
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
33,173
4,858
I see, in that case I should use arrayList?
Might be a good idea.
 
  • #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]);
        }
    }
}
 

Related Threads for: Java: Reading a file into an array

Replies
6
Views
2K
Replies
6
Views
19K
  • Last Post
Replies
6
Views
2K
Replies
2
Views
3K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
6
Views
3K
Top