【问题标题】:Trying to read a txt file in android试图在android中读取一个txt文件
【发布时间】:2013-04-24 01:17:52
【问题描述】:

我正在尝试读取项目中的 txt 文件。我不断收到异常 FileNotFound 并且不知道为什么。该文件位于 AnroidManifest XML 下的项目文件夹中,但无论如何它都非常适合对我隐藏。请帮忙,因为我快要疯了,对此感到沮丧。我知道我可以使用 Raw 和 Assets 来读取 txt 文件,但我需要能够写入这个 txt 文件以及读取它。

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

}

【问题讨论】:

  • 您是否尝试将文件存储在 /assets 子文件夹中? AssetManager 提供对资产原始文件的访问。
  • 如果你看这里:stackoverflow.com/questions/3760626/… 它说我无法写入资产文件。我需要既能写信又能读。

标签: android file-io


【解决方案1】:

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

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

阅读:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 如何从本地方法读取文件?我使用了类似的方法,但得到了errors 如何解决?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2020-03-09
    相关资源
    最近更新 更多