Reputation: 1338
I have a .txt file which contains a list of stuff I want to store in an Array and use throughout my application. To achieve this I created the following class:
public class Sort {
ArrayList<String> sorted = new ArrayList<String>();
public Sort() throws IOException {
Scanner scanner = new Scanner(new FileReader("/home/scibor/coding/src/com/myapp/readThis.txt"));
while(scanner.hasNextLine()){
sorted.add(scanner.nextLine());
}
}
}
So I have a .txt file with a bunch of stuff in it, and then I create this class specifically for that case. Now when I want to access these things in the .txt file in an ArrayList in one of my other classes, I figure:
Sort sort = new Sort();
sort.sorted; //can use the arrayList like so
Instead I get a message that says UnhandledException: java.io.IOException
I've tried several variations of this using try/catch, BufferedReader with try/catch/finally and ultimately all of them have some sort of error pertaining to the Exceptions that are raised by reading in a file. What am I doing wrong here?
EDIT: As per one of the suggestions, I have tried a radically different approach as below:
public class Sort {
List<String> sorted;
public Sort(Context context){
sorted = new ArrayList<String>();
AssetManager assetManager = context.getAssets();
try {
InputStream read = assetManager.open("readThis.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(read));
while(reader.readLine() != null){
sorted.add(reader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This seems to get me further, and is probably very close to the correct answer. When I create Sort mySortedObject = new Sort(this);
there are no errors generated. When I finally access the ArrayList though, as follows:
for(String name: mySortedObject.sort){
if(name.equals("Whatever"){
//run this
}
}
}
I get a NullPointerException on the line containing the if
statement. So the object was successfully created...but not quite?
EDIT: The "readThis.txt" file is located in /assets
Upvotes: 0
Views: 51
Reputation: 13351
I believe the file "/home/scibor/coding/src/com/myapp/readThis.txt" does not exist on your phone (and for a good reason). You will need to add your .txt as an asset to your project and load it using the AssetManager.open()-method
Edit:
In your edited code, your NullPointerException
is caused by you calling .readLine() twice in each iteration.
Solution:
String line = null;
while(true){
line = reader.readLine();
if (line == null) break;
sorted.add(line);
}
Upvotes: 2