heyman heyman - 1 year ago 74
Java Question

java: about read txt file into array

i want read txt file into array.

In the array, how can i do that? data = new String[lines.size]

i dont want to hard code 10 in the array.

My code:

BufferedReader abc = 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();

Answer Source

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[]{});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download