Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

akou
831 PointsRead lines of a text file into an array
Hi everyone,
In android studio where should I put my text file that contains at each line a different text. Then how can I read this text file and put each line into an array? I would like to use that to display a new quote randomly every time someone launch the app.
I found this code, but it doesn't seems to work :
// set up variables
String fileName = "MyFriends.txt";
String line;
ArrayList aList = new ArrayList();
//Read the lines of text into an ArrayList
try {
BufferedReader input = new BufferedReader(new FileReader(fileName));
if (!input.ready()) {
throw new IOException()
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
System.out.println(e);
} '''
Thanks
1 Answer

Tyler Russell
3,007 PointsOne thing you might want to change is the data type of the ArrayList. You would want to have it a String: ArrayList<String> list = new ArrayList<String>();
akou
831 Pointsakou
831 PointsThanks but I don't really get what you mean, like that : String aList = new ArrayList(); ? Also I don't know in which folder of the project I shoud put by text file.
Tyler Russell
3,007 PointsTyler Russell
3,007 PointsMake this line of yours: ArrayList aList = new ArrayList();
to this one: ArrayList<String> aList = new ArrayList<String>();
ArrayLists need a data type (non-primitive). This might not solve your problem, but it is a start.