0

I am trying to load in a file and I am getting a FileNotFoundException even though the file is present. I have tried doing the absolute path (C:/Users/cdeck_000/AndroidStudioProjects/ProjectCaligula_Final/cert/cert.crt) and the relative path (cert/cert.crt) assuming Android starts at the project level. When I run it using the relative path and ask for the file absolute path I get this:

Path: /cert/cert.crt

The code is below along with the project structure.

File file = new File("cert/cert.crt");
boolean i = file.exists();  //false
boolean r = file.canRead(); //false
String path = file.getAbsolutePath(); //cert/cert.crt
String pathForApp = new File(".").getAbsolutePath(); //returns "/."
InputStream caInput = new BufferedInputStream(new FileInputStream(file)); //error

File Structure

Can anyone chime in and let me know if my knowledge of absolute/relative paths with Android is wrong or give me advice on how to solve this? I have already thought that permissions was the issue but I raised the files permissions (equivalent to chmod 777) and it didn't change anything.

Chris Deck
  • 146
  • 2
  • 9
  • Your IDE will normally execute your application from the `build` or `build/classes` directory. Your certificate file should therefore have been placed in the `src` directory, for copying into the class directory. – user207421 Mar 22 '17 at 05:20
  • @EJP thanks.. I moved the file into src so now the path is ../src/cert.crt .. I changed the file to load from "cert.crt" now but it still isn't finding it. – Chris Deck Mar 22 '17 at 05:25
  • Maybe I am wrong, your file resides on the hard disk of your machine and when you run the app, your app can't access your machine's hard disk. And maybe because of `File file = new File("cert/cert.crt");` you are getting the paths as a string, but not accessible when running the app on emulator/device. Try to read the file by putting it in res/raw or assets folder. – knownUnknown Mar 22 '17 at 05:26
  • If you want it to be in `cert/cert.crt` you need to put it into `src/cert/crt`. But really that makes it a resource, not a file, so you should be using `Class.getResourceAsStream("/cert/cert.crt")`, not `new FileInputStream().` – user207421 Mar 22 '17 at 05:32
  • @EJP that was it! Wow, so simple and didn't realize it. Thanks for the help. Answer the question and I will mark it as correct. – Chris Deck Mar 22 '17 at 05:43

1 Answers1

2

You should put it into src/cert/cert.crt, which makes it a resource, not a file, so you should use Class.getResourceAsStream("/cert/cert.crt"), not new FileInputStream().

user207421
  • 305,947
  • 44
  • 307
  • 483