1

This is a chunk of data I'd like to access by a method. I'm doing the following to read my file:

String fileName = "file.txt" 
InputStream inputStream = new FileInputStream(fileName);
BufferedReader bufferedReader = new BufferedReader(new       InputStreamReader(inputStream));

My file.txt is in the same package, but I still get FileNotFoundException. I didn't use a path url to point to the file because I thought since this it going to be an android application, hard-coding the path might not work when deployed... Please correct me if I am wrong. Thanks bunch!

antoniodvr
  • 1,259
  • 1
  • 14
  • 15
Jay Xu
  • 13
  • 1
  • 5

2 Answers2

1

This shows how to do that. https://stackoverflow.com/a/14377185/2801237

Also the 'package' your class is in has nothing to do with the 'path' where the file is being executed from. (two different concepts, 'package' = folder hierarchy of java source code files), 'path' = location on a filesystem of a specific file, your APK is being 'executed' in a particular place, and the location it writes a file is associated with that (I actually don't know where 'offhand' it writes by default, because I always get cache dir, or sd card root, etc.)

Community
  • 1
  • 1
mawalker
  • 2,072
  • 2
  • 22
  • 34
  • Thank you for explaining the differences. So you are saying it is OK for me to reference to the file using the path it is located inside the filesystem for an android application? – Jay Xu Dec 20 '15 at 22:03
  • yes, but check to make sure the file still exists when you try to read it (good practice) – mawalker Dec 20 '15 at 23:02
1

You may use:

InputStream inputStream = this.getClass().getResourceAsStream(fileName);
Ugur Ozmen
  • 580
  • 3
  • 10