Reading a text file into an array

I want to read a text file in an array. How can i do this?

data = new String[lines.size]

I do not want to hard code 10 in an 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();
+5
source share
3 answers

Use an ArrayList or other dynamic data structure:

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[]{});
+7
source

Use instead List. In the end, if you want, you can convert it back to String[].

BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> data = new ArrayList<String>();
String s;
while((s=abc.readLine())!=null) {
    data.add(s);
    System.out.println(s);
}
abc.close();
+2
source

dtechs, ArrayList, 2 : -, .

+1

All Articles