Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text file into an array

Tags:

java

I want read a text file into an array. How can I do that?

data = new String[lines.size]

I don't want to hard code 10 in the array.

BufferedReader bufferedReader = new BufferedReader(new FileReader(myfile));
String []data;
data = new String[10]; // <= how can I do that? data = new String[lines.size]

for (int i=0; i<lines.size(); i++) {
    data[i] = abc.readLine();
    System.out.println(data[i]);
}
abc.close();
like image 992
heyman Avatar asked Apr 21 '12 10:04

heyman


1 Answers

Use an ArrayList or an other dynamic datastructure:

BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> lines = new ArrayList<String>();

while((String line = abc.readLine()) != null) {
    lines.add(line);
    System.out.println(data);
}
abc.close();

// If you want to convert to a String[]
String[] data = lines.toArray(new String[]{});
like image 115
dtech Avatar answered Sep 18 '22 00:09

dtech