0

I'm developing an app for Android, and I've run into a problem. Using the following 2 objects I have successfully written data to a file. I've checked this using the android file explorer.

FileOutputStream outFile = openFileOutput("myfile.dat", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(outFile);

File's output is as follows. Underscore represents an empty line.

1
2
3
4
5
_

Later in this code, an instance of ThingTable needs to be initialized. A filename is required for ThingTable's constructor. ThingTable goes through, and grabs the data line by line from myfile.dat. I use a Scanner variable to try to read from the file. Here is the code from the constructor. I've checked, and filename is myfile.dat

Scanner scan = new Scanner(new File("myfile.dat"));

while(scan.hasNextLine())
{
    String t1 = scan.nextLine();
    String t2 = scan.nextLine();
    String t3 = scan.nextLine();
    String t4 = scan.nextLine();
    String t5 = scan.nextLine();
    addItem(new ThingNode(t1, t2, t3, t4, t5));
}

scan.close();

When this code runs, I get a FileNotFound exception. Why can't this code find the file?

Sidenote: I acknowledge an error in my read function. The constructor will try to read lines that don't exist. That's not the issue here.

DeepDeadpool
  • 1,441
  • 12
  • 36

1 Answers1

0

When you use the openFileOutput() method, the file is created in a directory under your app's location, e.g. /data/data/yourapp/files. When you create a File object without the appropriate pathname as you have, it's basically looking in the wrong place. In your case, you simply need to use openFileInput() and an InputStreamReader to retrieve the contents.

If you want the absolute path to your app's files directory, you can use the getFilesDir() method.

Mike M.
  • 38,532
  • 8
  • 99
  • 95
  • Thanks! None of those methods were ever recognized in my class, but I hardcoded the path and it worked. – DeepDeadpool Mar 15 '14 at 10:50
  • @user3263864, I'm glad you got it working. But I'm curious. If `openFileOutput()` was recognized, the others should be as well. What class are you working in? – Mike M. Mar 15 '14 at 11:01
  • Ah, I should learn to read. Right, your ThingTable class. The methods I mentioned are members of the Context class. If you were to pass your Activity's Context in the constructor, you would have those methods. Actually, getApplicationContext() might work as well. I'd have to check, though. – Mike M. Mar 15 '14 at 12:36