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();
    }
}

}

4

2 回答 2

2

不要将文件存储在资产中。转到 YourProject/res 并创建一个名为 raw 的目录并将其存储在那里。

您也可以将文件存储在内部存储中,但我怀疑 res/raw 方法更适合您的目的。

读这个:

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

于 2013-04-24T01:57:13.153 回答
0

您不能将文件放在清单文件也存在的应用程序的主文件夹中。openFileInput("filenames.txt") 函数仅在您尝试读取或写入存在于手机内存中以下路径的文件时才有效

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

您可以做的一件事是当您第一次运行应用程序时保存文件,然后再读取或写入该文件。

于 2013-04-24T02:18:18.813 回答