0

I'm attempting to read a txt file I have in my project. I keep getting the exception FileNotFound and have no idea why. The file is in the project folder under the AnroidManifest XML, but yet it is great at hiding from me anyway. Please help because I am about to go crazy getting frustrated with this. I know I can use Raw and Assets to read txt files, but I need to be able to write to this txt file as well as read it.

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FileInputStream getIn;
    try {
        getIn = openFileInput("filenames.txt");
        //Creating an InputStreamReader and setting my FileInputStream
        InputStreamReader read = new InputStreamReader(getIn);
        //Creating a new BufferReader and adding the InputStreamReader
        BufferedReader dis = new BufferedReader(read);
        Toast.makeText(getApplicationContext(), dis.readLine(), Toast.LENGTH_SHORT).show();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • Have you tried storing a file in /assets subfolder? AssetManager provides access to assets raw files. – Whome Apr 24 '13 at 01:29
  • If you look here: http://stackoverflow.com/questions/3760626/how-to-write-files-to-assets-folder-or-raw-folder-in-android it says I can't write to asset files. I need to be able to write to them as well as read them. – user2313513 Apr 24 '13 at 01:31

2 Answers2

2

Don't store your file in assets. Go to YourProject/res and create a directory called raw and store it there.

You could also store your file in internal storage, but I suspect the res/raw approach is better for your purposes.

Read this:

http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

MarsAtomic
  • 10,436
  • 5
  • 35
  • 56
0

You can't put files in application's main folder where Manifest file also exist. openFileInput("filenames.txt") function only works when you are trying to read or write a file that exists at following path on phone's internal memory

/data/data/<application-package>/files/<file-name>

One thing that you could do is when you run application for the first time save your file and then later on read or write that file.

Sharjeel
  • 15,588
  • 14
  • 58
  • 89
  • how to read a file from native methods? I used a similar approach but am getting [errors](http://stackoverflow.com/questions/33124751/fatal-signal-11-error-read-a-file-from-a-native-method-in-ndk-eclipse) How to fix it? – re3el Oct 14 '15 at 15:04