Results 1 to 2 of 2
- 10-01-2007, 08:22 PM #1Member
- Join Date
- Jun 2007
- Rep Power
Reading in data from file line by line
I'm working on a project that takes a file filled with lines of integers and I want to take each line and store it into an array.
So for example:
5 6 3 5 4 5 8 7 9
2 6 5 4 9 8 8 6 6
3 1 2 6 5 4 8 9 5
3 3 2 1 5 6 5 8 4
I want to read each line of those integers into an array. So the first line would be its' own array, line 2 would be its' own array, so on and so forth. Assume you know the size of the arrays (in this case let's say nine).
- 10-02-2007, 12:19 AM #2
Some ideas. You could read the file, counting the number of lines, make your two-dimensional array with the number of lines. Then read it again and split each line into an array of Strings and parse each one to an int for the line array of ints.
Or you could start with a zero-length array, read the file once, parse each line to ints for the line array and add it to the array.
Or you could read the entire file as a string, count the number of lines and proceed as before.
You could use a BufferedReader or a Scanner for reading the file.
// Zero-length array int arrayOfInts = new int; // Split a String String line = reader.readLine(); String tokens = line.split("\\s"); You could use a BufferedReader for the above or a Scanner. // Add a line array to the array int len = arrayOfInts.length; int temp = new int[len]; System.arraycopy(arrayOfInts, 0, temp, 0, len); temp[len] = newLineArray; arrayOfInts = temp; // For a BufferedReader BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(arg)))
- By Azndaddy in forum New To JavaReplies: 2Last Post: 04-06-2012, 08:00 AM
- By Java Tip in forum java.langReplies: 0Last Post: 04-04-2008, 02:48 PM
- By Java Tip in forum Java TipReplies: 0Last Post: 01-18-2008, 11:52 AM
- By ramachandran in forum New To JavaReplies: 2Last Post: 10-24-2007, 07:22 AM
- By jdepue in forum Advanced JavaReplies: 1Last Post: 08-01-2007, 04:58 AM