在应用程序的内部存储中创建子目录时删除“app_”前缀

时间:2013-01-20 07:07:00

标签: android

Android提供了许多用于在设备上持久存储数据的选项。我选择internal storage,所以请不要提出存储在SD卡上的建议。 (我已经看到太多关于内部存储的问题有SD卡的答案!!)

我想在应用程序的内部存储目录中创建子目录。我跟着this SO answer,转载如下。

File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.

不幸的是,那是用“app_”前缀创建子目录。因此,从示例中,子目录看起来像“app_mydir”(不理想)。

The answer to this SO question建议你可以这样摆脱“app_”前缀:

m_applicationDir = new File(this.getFilesDir() + "");
m_picturesDir = new File(m_applicationDir + "/mydir");

但我想写一个像/data/data/com.mypackages/files/mydir/the.zip这样的拉链。

所以,最后,我的代码看起来像这样:

File appDir = new File(getApplicationContext().getFilesDir() + "");
File subDir = new File(appDir + "/subDir");
File outFile = new File(subDir, "/creative.zip");

但是,当我尝试这个时,这会产生另一个错误:“文件不存在”:

FileOutputStream fileStream = new FileOutputStream(outFile);

我怎样才能(1)创建一个没有“app_”前缀的子目录,以及(2)在其中写一个zip?

另外,如果我的第一个要求不合理,请在评论中告诉我原因!我确信“app_”前缀有一些让我无法理解的意思。

1 个答案:

答案 0 :(得分:9)

您是否创建了目录?

File appDir = getApplicationContext().getFilesDir();
File subDir = new File(appDir, "subDir");
if( !subDir.exists() )
    subDir.mkdir();
File outFile = new File(subDir, "creative.zip");

请注意,您不应在应用中的任何位置使用/,以防它发生变化。如果您确实想要创建自己的路径,请使用File.separator