Link to home
Start Free TrialLog in
Avatar of jowens1023
jowens1023Flag for United States of America

asked on

Need help w/ File input, read in line by line into array.

I need to prompt the user to enter a file name, read that file line by line.  Each line in the file has four parts seperated by a space.  Need to put these objects in an array.

I'm new to Java and programing, and am having a hard time figuring this out or finding examples.

Thanks,
Jim
Avatar of StillUnAware
StillUnAware
Flag of Lithuania image

BufferedReader rf = new BufferedReader(new FileReader("filename"));

String line = rf.readLine(); //reads a line from file

String[] parts = line.split("\s"); //splits line into strings, delimeter is white space (space, tab, new line, carriage return...)
Avatar of vinlnx
vinlnx

And to read in the whole file and nothing more put what StillUnaware said: "String line = rf.readLine(); //reads a line from file" into a while loop and check if the file has any more lines to read like so:

while(rf.ready()){
String line = rf.readLine(); //reads a line from file
}
Avatar of jowens1023

ASKER

Thanks StillUnAware and vinlx,

That helps, but how do I get the lines into an array?

Thanks,
Jim
BufferedReader rf = new BufferedReader(new FileReader("filename"));
while(rf.ready()){
  ArrayList al = new ArrayList();
  al.add(rf.readLine()); //reads a line from file and adds to ArrayList
}
Object[] objArray = al.toArray();
String[] lines = new String[objArray.length];
for(int i = 0; i < objArray.length; i++)
  lines[i] = (String)objArray[i];

now 'lines' will contain lines from file 'filename'
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This *also* looks like homework - have you finished it now guys?