Reading a File Into an Array Java

You are using an out of date browser. Information technology may not display this or other websites correctly.
Yous should upgrade or use an culling browser.
  • Forums
  • Homework Assistance
  • Applied science and Comp Sci Homework Help

Java: Reading a file into an array

  • Comp Sci
  • Thread starter Robben
  • Kickoff date

Homework Statement

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

Homework Equations

None

The Attempt at a Solution

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

                            public class exercise {     public String[] assortment;     Scanner inputStream = null;     Scanner n = new Scanner(Arrangement.in);       public String line;        public practice(Cord theFile) {                array = new String[150];         effort {                       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 hither                            }              }                      } grab(FileNotFoundException due east) {              Organisation.out.println(e.getMessage());          }          inputStream.close();         } }                          
Last edited:

Answers and Replies

Some notes on your code:

Yous're not reading in the adjacent line in your while loop. Since it never reads the second line, it won't ever become out of the loop.

You probably want to use i instead of 0 hither .
Some notes on your lawmaking:

You're not reading in the side by side line in your while loop. Since it never reads the second line, it won't ever exit of the loop.

You probably want to use i instead of 0 here .

But fifty-fifty if I do array = line it still won't take in whatever lines into the array.
Note that when we put i inside of brackets [] outside of a lawmaking block, the forum's software is treating that as a marker to plow the rest of the mail service into italics.
But even if I practice array = line information technology still won't accept in whatever lines into the assortment.

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

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

Note that when we put i inside of brackets [] outside of a code cake, the forum's software is treating that equally a marking to turn the rest of the postal service into italics.

Earlier your while loop, yous accept this code that reads in the starting time line of the file:

This reads the beginning line of the file and assigns information technology to the variable 'line'.

Your while loop uses inputStream.hasNextLine() to see if there is some other line available. All the same, that doesn't read in the next line from the file. It just looks ahead to run across if something is there. So your code only 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 volition never go out 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:
                          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 side by side line. In BufferedReader we have readLine(), merely I am non certain what to do with scanner.

Hither is my BufferedReader which works fine:
                              br = new BufferedReader(new FileReader(fileName)); line = br.readLine();  while ((strLine = br.readLine()) != nix) {     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 non certain what to do with scanner.

At that place's the nextLine() method in the Scanner course. That should work for you lot. 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 in a higher place, there's a lot of extra movement that isn't needed. For instance, you have a for loop nested inside your while loop. I don't run across whatsoever need for the for loop. I call back the following would work.

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

The basic thought is this:
Read a line, and store it in strLine.
If the line read was an empty string, get out 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.

Homework Argument

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

Homework Equations

None

The Endeavour at a Solution

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

                              public class practice {     public Cord[] array;     Scanner inputStream = nothing;     Scanner northward = new Scanner(System.in);     public String line;      public practice(String theFile) {             array = new Cord[150];         effort {                    inputStream = new Scanner(new FileInputStream(theFile));             line = inputStream.nextLine();              while (inputStream.hasNextLine()) {                 for (int i = i; i < assortment.length; i++){                     assortment[0] = line;                     //dont know what to put here                         }              }                   } catch(FileNotFoundException east) {              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/vii/docs/api/java/util/Scanner.html and on the same folio, http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine().

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

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

The bones idea is this:
Read a line, and shop 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 showtime the loop again.

I run into, thank you very much! I also merely got it to piece of work by taking out the while loop and only using the foor loop. My lawmaking now looks like this:
                          attempt {               inputStream =         new Scanner(new FileReader(fileName));     line = inputStream.nextLine();         for (int i = 0; i < array.length; i++) {         array[i] = inputStream.nextLine();       }          inputStream.close();           } take hold of(FileNotFoundException east) {        System.out.println(e.getMessage());      }                        
I encounter, thank yous very much! I also but got it to work by taking out the while loop and just using the foor loop. My code now looks similar this:
                              attempt {              inputStream =         new Scanner(new FileReader(fileName));     line = inputStream.nextLine();       for (int i = 0; i < array.length; i++) {         assortment[i] = inputStream.nextLine();      }         inputStream.close();          } take hold of(FileNotFoundException e) {        Arrangement.out.println(e.getMessage());      }                            
The problem with this approach is that if your array is alleged likewise small, your loop will end before all the lines are read from the input file. That's likewise a problem in the code I gave, so you need to make sure that you have some thought how big the input file is at compile time. 1 workaround is to use dynamic arrays, arrays that can be resized at run-time.
The problem with this approach is that if your array is alleged besides minor, 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 certain that yous have some idea how large the input file is at compile time. 1 workaround is to utilize dynamic arrays, arrays that can be resized at run-time.

I see, in that case I should use arrayList?
I see, in that example I should use arrayList?
Might be a good thought.
Here's a way to do this using the coffee.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
ii) reading in the file contents into a list of Cord and and then creating an assortment of Strings based on the size of the List and populating that assortment with the List of Cord

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

Solution 1:

                          import java.io.File; import coffee.io.IOException; import coffee.nio.file.Files; import java.util.Listing;  public class ReadFile_Files_ReadAllLines {   public static void main(String [] pArgs) throws IOException {     Cord 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:
                          import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Listing;  public form ReadFile_Files_ReadAllLines {     public static void chief(String [] pArgs) throws IOException {         String fileName = "c:\\temp\\2.sample-10KB.txt";         File file = new File(fileName);          List <Cord> fileLinesList = Files.readAllLines(file.toPath());         Cord [] fileLines = new String[fileLinesList.size()];         int i=0;         for(String line : fileLinesList) {             fileLines[i++] = line;         }                 for(int j=0; j<fileLines.length; j++) {             Arrangement.out.println("fileLines[" + j + "]=" + fileLines[j]);         }     } }                        

Related Threads on Java: Reading a file into an assortment

  • Last Post
  • Last Postal service
gabbagabbahey
  • Concluding Post
Mark44
  • Last Postal service
Mark44
  • Last Post
iamjon.smith
  • Last Mail
  • Last Post
iamjon.smith
  • Last Post
  • Last Mail
Mark44
  • Last Mail service
rcgldr
  • Forums
  • Homework Help
  • Engineering and Comp Sci Homework Aid

desrosierssympurs.blogspot.com

Source: https://www.physicsforums.com/threads/java-reading-a-file-into-an-array.804416/

0 Response to "Reading a File Into an Array Java"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel