在哪里存储FileInputStream中使用的文件

时间:2012-04-21 12:28:10

标签: android android-file

如果我想在我的android应用程序中使用FileInputStream来读取文件名,那么我应该在哪里保存文件。我可以将它保存在res / raw吗?

2 个答案:

答案 0 :(得分:1)

您无法在运行时将其保存在res / raw中,可以将其保存在SD卡或缓存目录中。

要将文件保存到SD卡,您必须具有写入卡的权限。您需要将以下内容添加到AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

接下来,打开文件流,写入文件流,然后在代码中的任何位置关闭它:

String filename = "filename.txt";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
    fos = new FileOutputStream(file);
    fos.write(data);
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    // handle exception
} catch (IOException e) {
    // handle exception
}

答案 1 :(得分:0)

如果要将文件包含在.apk中并在运行时读取它,则应将其放在项目的assets/文件夹中,然后使用:

InputStream istream = context.getAssets().open(FILE_NAME);

达到它。但是,如果您正在寻找从/ sdcard读取文件的方法,请参阅另一个答案。