1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java: Reading in file into an array

  1. Mar 21, 2015 #1
    1. The problem statement, all variables and given/known data

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

    2. Relevant equations

    None


    3. 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?

    Code (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: Mar 21, 2015
  2. jcsd
  3. Mar 21, 2015 #2

    Borg

    User Avatar
    Science Advisor
    Gold Member

    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.
     
  4. Mar 22, 2015 #3
    But even if I do array = line it still won't take in any lines into the array.
     
  5. Mar 22, 2015 #4

    Borg

    User Avatar
    Science Advisor
    Gold Member

    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.
     
  6. Mar 24, 2015 #5
    Here is my BufferedReader which works fine:

    Code (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.
     
  7. Mar 24, 2015 #6

    Mark44

    Staff: Mentor

    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.

    Code (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.
     
  8. Mar 24, 2015 #7
    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:

    Code (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());
         }
     
  9. Mar 24, 2015 #8

    Mark44

    Staff: Mentor

    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.
     
  10. Mar 24, 2015 #9
    I see, in that case I should use arrayList?
     
  11. Mar 24, 2015 #10

    Mark44

    Staff: Mentor

    Might be a good idea.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Java: Reading in file into an array
  1. Arrays in Java (Replies: 3)

  2. Reading a File (Replies: 2)

Loading...