How do you read the contents of a file into an ArrayList
in Java?
Here are the file contents:
cat
ho
You can for example do this in this way (full code with exceptions handlig):
BufferedReader in = null;
List myList = new ArrayList();
try {
in = new BufferedReader(new FileReader("myfile.txt"));
String str;
while ((str = in.readLine()) != null) {
myList.add(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}