如何在Androids'/ data / data / pkg / files'目录中创建文件层次结构?

时间:2009-12-11 16:26:15

标签: android file

我尝试在Android的/ data / data / pkg / files目录中创建'foo / bar.txt'。

这似乎是文档中的矛盾:

  

要写入文件,请使用名称和路径调用Context.openFileOutput()。

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

  

要打开的文件的名称;不能包含路径分隔符。

http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String,%20int)

当我打电话

this.openFileOutput("foo/bar.txt", Context.MODE_PRIVATE);
抛出异常:

java.lang.IllegalArgumentException: File foo/bar.txt contains a path separator

那么如何在子文件夹中创建文件?

5 个答案:

答案 0 :(得分:13)

看起来您遇到了文档问题。如果深入研究ApplicationContext.java的源代码,事情看起来就不会更好。在openFileOutput()里面:

File f = makeFilename(getFilesDir(), name);

getFilesDir()始终返回目录“files”。并makeFilename()

private File makeFilename(File base, String name) {
    if (name.indexOf(File.separatorChar) < 0) {
        return new File(base, name);
    }
    throw new IllegalArgumentException(
        "File " + name + " contains a path separator");
}

因此,通过使用openFileOutput(),您将无法控制包含目录;它总是会出现在“files”目录中。

但是,没有什么能阻止您使用File和FileUtils在包目录中自行创建文件。这只是意味着你会错过使用openFileOutput()给你的便利(例如自动设置权限)。

答案 1 :(得分:9)

您可以在私人目录中添加带有路径的文件,如

String path = this.getApplicationContext().getFilesDir() + "/testDir/";
File file = new File(path);
file.mkdirs();
path += "testlab.txt";
OutputStream myOutput;
try {
myOutput = new BufferedOutputStream(new FileOutputStream(path,true));
write(myOutput, new String("TEST").getBytes());
myOutput.flush();
myOutput.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

答案 2 :(得分:7)

使用getFilesDir()在您的软件包的File目录的根目录中获取files/

答案 3 :(得分:5)

要写入内部存储器子文件夹中的文件,首先需要创建文件(如果尚未存在,则需要创建子文件夹),然后创建FileOutputStream对象。

这是我使用的方法

    private void WriteToFileInSubfolder(Context context){
    String data = "12345";
    String subfolder = "sub";
    String filename = "file.txt";

    //Test if subfolder exists and if not create
    File folder = new File(context.getFilesDir() + File.separator + subfolder);
    if(!folder.exists()){
        folder.mkdir();
    }


    File file = new File(context.getFilesDir() + File.separator 
                         + subfolder + File.separator + filename);
    FileOutputStream outstream;

    try{
        if(!file.exists()){
            file.createNewFile();
        }

        //commented line throws an exception if filename contains a path separator
        //outstream = context.openFileOutput(filename, Context.MODE_PRIVATE);
        outstream = new FileOutputStream(file);
        outstream.write(data.getBytes());
        outstream.close();

    }catch(IOException e){
        e.printStackTrace();
    }
}

答案 4 :(得分:0)

假设原始帖子试图在文件区域中创建子目录并在其中写入文件,这可能是文档中的新内容:

public abstract File getDir (String name, int mode)

自:API Level 1

  

检索,根据需要创建应用程序所在的新目录   可以放置自己的自定义数据文件。您可以使用返回的文件   用于创建和访问此目录中的文件的对象。请注意文件   通过File对象创建的只能由您自己访问   应用;你只能设置整个目录的模式,而不是   个别档案。