Results 1 to 2 of 2
  1. #1
    bluekswing is offline Member
    Join Date
    Jun 2007
    Rep Power

    Default 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).

    Thoughts Suggestions?

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Rep Power


    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.
    Java Code:
    // Zero-length array
    int[][] arrayOfInts = new int[0][];
    // 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)))

Similar Threads

  1. [SOLVED] Delete Current line from file
    By Azndaddy in forum New To Java
    Replies: 2
    Last Post: 04-06-2012, 08:00 AM
  2. Replies: 0
    Last Post: 04-04-2008, 02:48 PM
  3. Reading a line from console using Scanner class
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-18-2008, 11:52 AM
  4. Reading Data from a file
    By ramachandran in forum New To Java
    Replies: 2
    Last Post: 10-24-2007, 07:22 AM
  5. Reading file data that contains no spaces
    By jdepue in forum Advanced Java
    Replies: 1
    Last Post: 08-01-2007, 04:58 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts