Reading in a file - java.io.FileNotFoundException

android, embedded-resource, file-io, filenotfoundexception, java

Solution

Because you're dealing with outside the package, `getResource()` will be the best solution for your problem:

URL url = getClass().getResource("/assets/levels.txt");
File f = new File(url.toURI());
//....

Or you can directly get the input stream using `getResourceAsStream()` method :

InputStream  is= getClass().getResourceAsStream("/assets/levels.txt");
isr = new InputStreamReader(is); 

It's better since you don't have to use FileInputStream.

Note that `URISyntaxException` must be caught with `FileNotFoundException` or declared to be thrown.

Problem

``` public void loadFile(int level){ try { //Create new file levelFile = new File("assets/levels.txt"); fis = new FileInputStream(levelFile); isr = new InputStreamReader(fis); reader = new BufferedReader(isr); //Code to read the file goes here ``` Using this code, however, I keep getting the above error (`java.io.FileNotFoundException`). The file definitely exists in my Assets folder and has the correct name. I've found a couple of similar questions on here and have tried various things including refreshing the project, cleaning the project, using `"levels.txt"` instead of `"assets/levels.txt"` but I keep getting this error. Any ideas why?

Original source