aspose file tools
The moose likes Java in General and the fly likes Read data from a file into a 2D array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Read data from a file into a 2D array" Watch "Read data from a file into a 2D array" New topic

Read data from a file into a 2D array

sony vijay
Ranch Hand

Joined: Jun 27, 2010
Posts: 32

Say, I have a file like so:


The first line represents the number of rows and the second line represents the number of columns. Thereafter, each line represents the data of a 2D array. I am using the following code to create a 2D array from the input file in Java.

The above code works. But, my task is to modify the code in order to create a 2D array from the array data directly without having to specify the rows/columns in the input file. The input file would now look like so:

My code should be able to read this file and dynamically create a 3*4 array. I am not sure how to do that. Thank You!

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11710

One way or another, you're going to have to read the whole file first so you know how big your array has to be.

Whether you do multiple passes through it, store it all in memory, use some other data structure as an intermediary, or something else, you HAVE to know the dimensions of the array before you can declare it.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Wendy Gibbons

Joined: Oct 21, 2008
Posts: 1107

does it have to be an array, is there any reason you couldn't use an ArrayList?
Joshi Nirav

Joined: Dec 04, 2009
Posts: 14

Hi all,

I think we can do it by this way.... This is a general Algorithm.

take some initial size of the No_Of_row = 2;
int oldData[] [] = null;
intialCounter = 0;
While(Read the File till EOF){
str := first line of the file.
col[] := split the 'str' by using the specific operator (In Our case its ',')
oldData = new int[No_Of_row][col.length];
if(initialCounter > No_Of_row){
int newData[][] = new int[initialCounter][col.length];
System.arrayCopy(oldata,0,newData,0,initialCounter - 1);
oldData[initialCounter - 1] = col;

Thanks and Regards
Nirav Joshi
I agree. Here's the link:
subject: Read data from a file into a 2D array