Reading file in a 2d Array

Hi there
I was wondering if anyone has some suggestions on how i can read a tab limited file in a two dimensional array. heres some i was trying but doesn't seem to get me the results i want
1) Read one line at a time into an array
2) Add the array to a list
3) convert the list to a twoD array.
the code is
List lines = new ArrayList();
int rowscount = 0;
String[] colHeader = new String[]{};
BufferedReader br = new BufferedReader(new FileReader(inFile));
String line = br.readLine();
while(line != null)
     //the first line contains column headers
     if (rowsCount == 0)
         colHeader = line.split("\t");
    else
         String[] tempVal = line.split("\t");
         lines.add(tempVal); //add to the list
         rowscount++;
         line = br.readLine();
String data[][] = new String[lines.size()][colHeader.length];
for (int i=0; i<lines.size(); i++)
     data[i] = (String[]) lines.get(i);
     for (int j = 0; j < colHeader.length; j++)
         logger.debug("DATA: "+data[i][j]);
     // this gives me arrayindexoutofboundexception
   } Well the error is coz the columnheaders are 16, but the actual data below column headers has only 10 columns and rest 6 are empty tabs...I want to include those empty tabs in the array(tempVal). Can anyone suggest me a better solution or modify this one so it works
Thanking you

Something like:
while (...) {
  String [] rowContents = line.split("\t");
  if (rowsCount == 0) {
    colHeader = rowContents;
  else {
    int numRemaining = colHeader.length - rowContents.length;
    if (numRemaining > 0) {
      List list = new ArrayList(Arrays.asList(rowContents));
      list.addAll(Collections.nCopies(numRemaining, ""));
      rowContents = (String [])list.toArray(rowContents);
      lines.add(rowContents);
  rowsCount++;
  line = br.readLine();
}

Similar Messages

  • Read file into multi-dimensional array - ideal world...

    Hello all, would be very grateful if you could help me...
    I have a file which has a format...
    string1a,string1b
    string2a,string2bi need to read this file, which will have a variable length, into a two dimensional array.
    the code below is just demonstrating my approach...
              List lines = new ArrayList();
              BufferedReader in = new BufferedReader(new FileReader(filename));
              String str;
              while ((str = in.readLine()) != null) {
                   lines.add(str.split(","));
              in.close();but when i later try and invoke the toArray() method of lines it complains about unsafe or unchecked operations.
    does any have any pointers about the best way to read a file into a multi-dimensional array? is it best practice to use the interface List?
    thanks in advance
    poncenby

    This is just a List of Lists - no worries there.
    Sounds like your toArray code is incorrect. Post that.
    %

  • Reading characters from a text file into a multidimensional array?

    I have an array, maze[][] that is to be filled with characters from a text file. I've got most of the program worked out (i think) but can't test it because I am reading my file incorrectly. However, I'm running into major headaches with this part of the program.
    The text file looks like this: (It is meant to be a maze, 19 is the size of the maze(assumed to be square). is free space, # is block, s is start, x is finish)
    This didn't paste evenly, but thats not a big deal. Just giving an idea.
    19
    5..................
    And my constructor looks like follows, I've tried zillions of things with the input.hasNext() and hasNextLine() to no avail.
    Code:
    //Scanner to read file
    Scanner input = null;
    try{
    input = new Scanner(fileName);
    }catch(RuntimeException e) {
    System.err.println("Couldn't find the file");
    System.exit(0);
    //Set the size of the maze
    while(input.hasNextInt())
    size = input.nextInt();
    //Set Limits on coordinates
    Coordinates.setLimits(size);
    //Set the maze[][] array equal to this size
    maze = new char[size][size];
    //Fill the Array with maze values
    for(int i = 0; i < maze.length; i++)
    for(int x = 0; x < maze.length; x++)
    if(input.hasNextLine())
    String insert = input.nextLine();
    maze[i][x] = insert.charAt(x);
    Any advice would be loved =D

    Code-tags sometimes cause wonders, I replaced # with *, as the code tags interprets # as comment, which looks odd:
    ******...*.........To your code: Did you test it step by step, to find out about what is read? You could either use a debugger (e.g., if you have an IDE) or system outs to get a clue. First thing to check would be, if the maze size is read correctly. Further, the following loops look odd:for(int i = 0; i < maze.length; i++) {
        for(int x = 0; x < maze.length; x++) {
            if (input.hasNextLine()) {
                String insert = input.nextLine();
                maze[x] = insert.charAt(x);
    }Shouldn't the nextLine test and assignment be in the outer loop? And assignment be to each maze's inner array? Like so:for(int i = 0; i < maze.length; i++) {
        if (input.hasNextLine()) {
            String insert = input.nextLine();
            for(int x = 0; x < insert.size(); x++) {
                maze[i][x] = insert.charAt(x);
    }Otherwise, only one character per line is read and storing a character actually should fail.

  • Reading a CSV file and producing an array of objects

    Hi everybody,
    I am writing an application which will read a cvs file and produce an array of objects.
    Can any body help me to solve this problem?
    Thanks
    Finny

    Hello,
    Have you tried this link?
    http://ostermiller.org/utils/CSV.html

  • Reading from a text file in to an array, help please

    I have the following
    public class date extends Loans{
    public int dd;
    public int mm;
    public int yyyy;
    public String toString() {
    return String.format( "%d,%d,%d", mm, dd, yyyy );
    public class Loans extends Borrowing {
    public String name;
    public String book;
    public date issue;
    public char type;
    public String toString(){
    return String.format( "%s, %s, %s, %s", name, book, issue, type );
    import java.util.Scanner;
    import java.io.*;
    public class Borrowing extends BorrowingList {
    private Loans[] Loaned = new Loans[20];
    if i want to read in from a text file in to that array how do i do it?

    sorry to keep bothering you and thanks loads for your help but now I am getting the following error mesage
    C:\Documents and Settings\MrW\Menu.java:43: cannot find symbol
    symbol : class IOException
    location: class Menu
    }catch(IOException e){
    Note: C:\Documents and Settings\MrW\Borrowing.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    1 error
    BUILD FAILED (total time: 0 seconds)
    for this line
    }catch(IOException e){                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Reading file from a folder : File dir = new File(URL+aFile_to_add);

    Hi,
    Trying to read files from a dir on my site using a JSP and bean. I've tried nearly every option for the filepath I can think of and it doesn't seem to be finding the file...
    Here's the bit:
    String URL = "images\\wedding_photos\\";
    File dir = new File(URL+aFile_to_add);
    String[] files = dir.list();
    It's working locally, but I obviously had to change the path from c://... to the above.
    The full code is listed below in the addWedding Method
    The method removes the .jpg from the file name and then writes the new file name to a database
    Thanks for any insight.
    Regards
    Jim
    public String addWedding(String aFile_to_add)
    String feedback = "unset in scrubWedding";
    try
    String URL = "images\\wedding_photos\\";
    Class.forName("org.gjt.mm.mysql.Driver");
    java.sql.Connection connection = java.sql.DriverManager.getConnection("jdbc:mysql://localhost/rhwedd2_shop?user=**********&password=*******");
    java.sql.Statement statement = connection.createStatement();
    File dir = new File(URL+aFile_to_add);
    String[] files = dir.list();
    if (files == null)
    feedback = "Sorry, couldn't find the file "+aFile_to_add+"...no files have been added.";
    else
    for (int i=0; i<files.length; i++)
    // Get filename of file or directory
    String filename = files;
    String no_extension;
    //convert string array element into a char array
    char [] charsfilename = filename.toCharArray();
    int newlength = charsfilename.length -4;
    no_extension = String.valueOf(charsfilename,0,newlength);
    filesAdded = filesAdded+", "+no_extension;
    // Show the new file names in stack trace without extension
    //System.out.println("String no_extension " + no_extension );
    statement.executeUpdate("INSERT INTO items VALUES ('"+no_extension+"',5,'"+aFile_to_add+"')");
    // write to table with item_id and weddingid
    feedback = "The following files have been added..."+filesAdded;
    if (statement != null )
    statement.close();
    if ( connection != null )
    connection.close();
    catch(Exception e)
    feedback = "Into the catch";
    e.printStackTrace(System.err) ;
    return feedback;
    }//end addWedding

    String URL = "images\\wedding_photos\\";
    File dir = new File(URL+aFile_to_add); ok, ok, I'll answer...
    1) What gives you the impression that the relative directory "images\\..." exists (or, in other words, what makes you think your current directory is the parent of "images"?

  • How to copy data in text file into two-dimensional arrays?

    Greeting. Can somebody teach me how to copy the input file into two-dimensional arrays? I'm stuck in making a matrix with number ROWS and COLUMNS according to the data in "input.txt"
    import java.io.*;
    import java.util.*;
    public class array
        public static void main (String[] args) throws FileNotFoundException
        { Scanner sc = new Scanner (new FileReader("input.txt"));
            PrintWriter outfile = new PrintWriter("output.txt");
        int[][]matrix = new int[ROWS][COLUMNS];
    }my input.txt :
    a,b,c
    2,2,1
    1,1,1
    2,2,1
    3,3,1
    4,4,1
    5,5,1
    1,6,2
    2,7,2
    3,8,2
    4,9,2
    5,10,2

    import java.io.*;
    import java.util.*;
    public class array {
        public static void main(String[] args) throws IOException {
            FileInputStream in = null;
            FileOutputStream out = null;
    try {
        in = new FileInputStream("input.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            String split[]=line.split(",");
    catch (IOException x) {
        System.err.println(x);
    } finally {
        if (in != null) in.close();
    }}}What after this?

  • Read file line by line

    Hi
    Could somebody tell me how to read file line by line ? Namely my input file I want to read look as follow:
    AAA 1, 1
    12 222 12
    AAA 2, 2
    11 122 11
    My output file should look as follow:
    1, 1, 12
    1, 1 222
    1, 1, 12
    2, 2, 11
    2, 2, 122
    2, 2, 11
    I think the lines need to be stored in ArrayList, then I would like those lines to write to csv file, but how on read I can construct such output file? This is my code for reading file
    public ArrayList readFile(String filename)
      try
         BufferedReader in = new BufferedReader(new FileReader(filename));
         ArrayList list = new ArrayList();
         String lineS = null;
         while (in.ready())
          if ((lineS = in.readLine()).startsWith("")){
            String[] line = in.readLine().trim().split("\\s+");
            list.add(Integer.valueOf(line[0]));
            list.add(Integer.valueOf(line[1]));
            list.add(Integer.valueOf(line[2]));
         in.close();
         return list;
         catch (Exception e)
       e.printStackTrace();
    return null;
    Thanks

    The rules for the conversion from input to the desired output are:
    1. For each of the line with string take 2 integers for example 1, 1  from AAA 1, 1
    2. Then repeat 1, 1 for each next number not containing any string, so if the line after AAA, 1, 1 has 12, 222, 12 then the output will look as follow
    1, 1, 12
    1, 1 222
    1, 1, 12
    3. Repeat the process (the pattern is the same 1 line with string 1 line with numbers)
    Actually I am not sure how to perform that logic for such conversion as for now I am only able to list only the numbers but I have a problem to add numbers from the line having string in it.
    STOP!
    You should NOT be writing code if you are 'not sure how to perform that logic'.
    You are getting ahead of yourself.
    There is NOTHING to gain by trying to code a solution before you know what algorothm you need. Big mistake.
    Should I use list or maybe if the patter for lines is the same array will be more sufficient?
    NEITHER ONE!
    Those are 'solutions' used to implelment an algorothm.
    You do NOT yet know what algorithm you need to use so how can you possibly write code to implement the unknown?
    How to perform logic to get the numbers from line having string and for the next lines having only numbers in order to structure it into desired output? 
    THAT is the question your thread subject should have.
    Until you get the answer to it don't write any code,.
    Do NOT try to automate what you can't do manually.
    Write down, on paper or use an editor, the step by step 'logic' you need and walk through that logic from beginning to end until the 'logic' works and produces the correct result.
    You just now have started to do that when you listed those rules above.
    But you left some things out. Expand on that list of 'rules' and provide a little more example data. TPD has given you a good example. Reread what they said.
    Did you notice they start by talking about 'tasks': what each task does and the order the tasks need to be performed.
    That 'task list' has NOTHING to do with Java, C, or any other language: it is identifying the problem/algorithm. Until you have that coding is premature.

  • Need help in reading file, got stuck

    The code below works sometimes sometimes gives a message problem finding/reading file
    public void readData()
    try
    DataInputStream dataIn = new DataInputStream(new FileInputStream("c://suneetha//data.txt"));
    for(i=0;i<3;i++)
    for(j=0;j<3;j++)
    goal[j] = (dataIn.readInt());
    dataIn.close();
    catch (IOException e){ System.out.println("problem finding/reading file");}
    catch (NumberFormatException nfe) { System.out.println("problem with format"); }
    public void writeData()
    int i=0,j=0;
    InputStreamReader is = new InputStreamReader( System.in );
    // Wrap input with a BufferReader to get
    // the readln() method to read a whole line at once.
    BufferedReader br = new BufferedReader( is );
    try {
    DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("c://suneetha//data.txt"));
    System.out.println("enter the array:");
    String s = br.readLine(); // Read the whole line
    st = new StringTokenizer(s);
    // With tokenizer nextToken() method we can ignore
    // any beginning and trailing white space.
    for(j=0;j<9;j++)
    i=Integer.parseInt(st.nextToken());//Convert string to int
    System.out.println( "got: " + i );
    j=i;
    dataOut.writeInt(j);
    catch (IOException ioe) {
    System.out.println( "IO error:" + ioe );
    not knowing what the problem is!!!
    some times it accepts data from file(for reading) some times it wont.
    I don't thing there is any problem with writing to the file
    Any help is greatly appreciated
    Thanks
    Suneetha.

    Are you not posting this for third time ( and with same problems.)
    Anyways.....
    for(i=0;i<3;i++)
    for(j=0;j<3;j++)
    goal[j] = (dataIn.readInt()); // ????You want them in a 2 d array ?then make goal
    int [][] goal = new int[3][3];
    And
    // use
    if( dataIn.available() > 0 ){
    goal[ i ][j] = dataIn.readInt();
    else{
      // Your "custom" messages
    }

  • Read file with nio and flush with servlet

    Can I read file, by using java.nio (for example by FileInputStream.getChannel()) and then flush the file content thru the servlet?
    I kwow about reading without java.nio, get a byte array and then flush it by httpservletresponse writer or outputstream, but I wish to know if it is possibile with java.nio reading.
    thanks

    I'm doing it only for file reading..
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();    
            FileInputStream fis = null;                               
            try
                String path = "/var/hello.txt";
                fis = new FileInputStream(path);       
                FileChannel channel =  fis.getChannel();
                ByteBuffer bb = ByteBuffer.allocate((int) channel.size());
                channel.read(bb);
                byte[] data2 = bb.array();
                channel.close();
                out.write(new String(data2));
            } catch (FileNotFoundException ex)
                ex.printStackTrace();
            } finally
                try
                    fis.close();
                } catch (IOException ex)
    ex.printStackTrace();
                out.close();
        }

  • Specifying byte stream type for Read File with Type Descriptor

    Hi.
    I'm trying to write a VI that reads an image file format that can have
    different datatypes. What I have so far is that I open the file, read
    the header, and get the width, height, number of frames, and datatype.
    I calculate number of pixels by nrows*ncols*nframes with no problem,
    but I'm not sure how to tell Read File the correct datatype to read
    the data into.
    I tried using a Case structure where I have a Read File in each case
    with the correct type constant as input for that case. The problem is
    that the tunnel graduates the datatype to the highest representation.
    I found in Application Note 154 the discussion about Type Descriptors.
    Is there a way to generate a Type Descriptor and output it from a C
    ase
    structure? I tried just returning the value (e.g. 0x0402 for a Word),
    but Read File will just see that the byte stream type is a uint32.
    Is there any other way to do this?
    Thanks for any help.

    I converted the code to LabVIEW 6.1 for you and attached it below.
    Don't worry about being a newbie. We all start there. Keep asking this type of question and you won't stay there long.
    As you are discovering, being strictly typed means that you must rewrite code even for a simple data type change, or convert everything to the same data type first. For image data, conversion can result in a lot of extra space being wasted. Use a modified version of the GLV_WaveformBuffer.vi to hold your data. Use the array functions, which operate inline, to add to and delete the data wires in the buffer. This allows you to save several different data types. You will need several different inputs and outputs to handle these data types. I ha
    ve also attached a similar file created for exactly the problem you have - storing arrays of different data types (data from NI-SCOPE devices, in this case - can be float, I8, I16, or I32).
    Routines that take any type work in one of two ways. LabVIEW primitives, such as plus and minus operators, work by figuring out the type and doing the right thing in the C code layer of the LabVIEW environment. Users of LabVIEW can't do this. Users can make polymorphic VIs. Polymorphic VIs are actually a single VI for every data type that are referenced by a "wrapper", the polymorphic VI. Users still need to write a different VI for every data type they need.
    Take home message - if you need to work with different data types, you will need to rewrite your code for every data type or convert your data to a common data type. Polymorphic VIs and case statements are your friend.
    Let me know if you need more help.
    This account is no longer active. Contact ShadesOfGray for current posts and information.
    Attachments:
    GigaLabVIEW61.zip ‏362 KB
    sfpScpChan_Waveform_Buffer.zip ‏74 KB

  • Error 1156 in LV7.0 when Read File

    Hello,
    we programmed a software with LV6.1.
    Now we use LV7.0 and we have a problem to open
    old binary data files with it. If we want
    to open a file with "Read File" it occurs the error
    "1156". We change nothing at these routines, everything
    works with LV6.1.
    Has anybody the same problem or know whats to do?
    Best Regards
    Patrick Frank

    Patric,
    This problem has already been reported to NI, and the LabVIEW team is currently investigating a solution. From what I can tell, it looks like the problem occurs when trying to read a datatype that is not in the file. This will result in the misleading out of memory dialog.
    Make sure that you specify the correct data type to read.
    Other than that, I have no workaround information.
    How Do I Read and Write an N-Dimensional Array to a File in LabVIEW
    Zvezdana S.
    National Instruments

  • Read file in chunks

    hello,
    as many of you know i'm trying to solve a problem memory with labview 7.1
    many of you told me to read file in chunks and i'm trying to do it...
    but i have some questions...
    in attachment you find see my VI (it's incomplete): i would read my files 1 Mb for each step (now my file is 80 Mb)...i would ask you what i have to link to count input of the readfile vi in the true case (the last for-cycle-step, where i have to save the last part of my file).
    Should it be correct done in this way?
    Have i done the save-process in the correct way? (initialize the array knowing the array size and the using the arrayreplacesubset vi in the for loop)
    thanks all
    Using LabVIEW 7.1
    Attachments:
    ReadFileInChunks.vi ‏58 KB

    EOF function give me the size of the file and not the offset of the EOF?
    so in which way could i stop the while cycle?
    yes,,,i'm reading the file line by line and the i'll concatenate strings (1000 in the example) to obtain a chunk of data
    if i put in the count input of the read file function (with the line mode True) i don't obtain all lines in the output...i don't know why
    you can see the image in attachment
    in fact was to solve my problem that i tryed to concatanate strings...if i could receive in the output 1000 lines in a automatic way should be better...
    and yes...in my case i'll make my operation in the case structure, when i obtaine 1000 lines
    Using LabVIEW 7.1
    Attachments:
    examplee.png ‏43 KB

  • File content as byte array ?

    I have the following code :
    File file = new File("path/to/file");
    And I want to get the content of "file" as a byte array, something like :
    byte[] byteArray = file.getContentAsByteArray();
    How do I achieve this ?
    Cheers !

    The following is also possible.
    //import java.io.*;import java.nio.channels.*;import
    java.nio.ByteBuffer;
    java.io.File file = new File("input.txt");
    FileInputStream stream = new FileInputStream(file);
    java.nio.channels.FileChannel
    channel=stream.getChannel();
    java.nio.ByteBuffer buffer =
    ByteBuffer.allocate((int)file.length());// if length
    is larger than Integer.MAX_VALUE iteration must be
    used
    channel.read(buffer);
    channel.close();
    stream.close();
    byte[] bytes = buffer.array();
    // for(int j=0;j<bytes.length;j++)
    System.out.println(Integer.toHexString(bytes[j]));
    This will, of course, only work in 1.4, because of the java.nio packages.

  • HOW TO DELETE ADOBE READER FILE FROM ADOBE READER

    HOW TO DELETE ADOBE READER FILE FROM ADOBE READER@ !@

    Your question make no sense. What exactly are you trying to do?

Maybe you are looking for