jowens1023
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
I'm new to Java and programing, and am having a hard time figuring this out or finding examples.
Thanks,
Jim
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
}
while(rf.ready()){
String line = rf.readLine(); //reads a line from file
}
ASKER
Thanks StillUnAware and vinlx,
That helps, but how do I get the lines into an array?
Thanks,
Jim
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'
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
This *also* looks like homework - have you finished it now guys?
:)
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...)