mahmood
mahmood

Reputation: 24795

reading file line by line and adding lines to array

I want to read a file line by line in Java. Each line is added as an item to an array. Problem is that, I have to create the array based on the number of lines in the file while I am reading line by line.

I can use two separate while loops one for counting and then creating the array and then adding items. But it is not efficient for large files.

try (BufferedReader br = new BufferedReader(new FileReader(convertedFile))) {
  String line = "";
  int maxRows = 0;
  while ((line = br.readLine()) != null) {
    String [] str = line.split(" ");
    maxColumns = str.length;
    theRows[ maxRows ] = new OneRow( maxColumns );   // ERROR
    theRows[ maxRows ].add( str );
    ++maxRows;
  }
}
catch (FileNotFoundException e) {
  System.out.println(e.getMessage());
}
catch (IOException e) {
  System.out.println(e.getMessage());
}

Consider private OneRow [] theRows; and OneRow is defined as String []. the file looks like

Item1    Item2   Item3   ...
2,3       4n     2.2n
3,21      AF     AF
...

Upvotes: 0

Views: 121

Answers (3)

Borislav Kostov
Borislav Kostov

Reputation: 68

Check ArrayList. ArrayList is resisable array.And is equivalent to C++ Vector.

try (BufferedReader br = new BufferedReader(new FileReader(convertedFile))) 
{ 
    List<String> str= new ArrayList<>();
    String line = ""; 
    while ((line = br.readLine()) != null) { 
    str.add(line.split(" "));
    } 
} 
catch (FileNotFoundException e) { 
 System.out.println(e.getMessage());
} catch (IOException e){ 
 System.out.println(e.getMessage()); 
}

Upvotes: 2

user7764066
user7764066

Reputation:

I would consider using the ArrayList data structure. If you are unfamiliar with how ArrayLists work I would read up on the documentation.

Upvotes: 0

Thomas
Thomas

Reputation: 182063

You can't resize an array. Use the ArrayList class instead:

private ArrayList<OneRow> theRows;

...

theRows.add(new OneRow(maxColumns));

Upvotes: 5

Related Questions