我尝试在Android的/ data/data/pkg/files目录中创建'foo/bar.txt'.
这似乎是文档中的矛盾:
要写入文件,请使用名称和路径调用Context.openFileOutput().
http://developer.android.com/guide/topics/data/data-storage.html#files
要打开的文件的名称; 不能包含路径分隔符.
当我打电话的时候
this.openFileOutput("foo/bar.txt", Context.MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)
抛出异常:
java.lang.IllegalArgumentException: File foo/bar.txt contains a path separator
Run Code Online (Sandbox Code Playgroud)
那么我如何在子文件夹中创建文件?
Dan*_*Lew 13
看来你遇到了一个文档问题.如果深入研究ApplicationContext.java的源代码,事情看起来就不会更好.在openFileOutput()里面:
File f = makeFilename(getFilesDir(), name);
Run Code Online (Sandbox Code Playgroud)
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");
}
Run Code Online (Sandbox Code Playgroud)
因此,通过使用openFileOutput()您将无法控制包含目录; 它总是会出现在"files"目录中.
但是,没有什么可以阻止您使用File和FileUtils在包目录中自己创建文件.它只是意味着你会错过使用openFileOutput()给你的便利(比如自动设置权限).
您可以在私有目录中添加带路径的文件
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();
}
Run Code Online (Sandbox Code Playgroud)
使用getFilesDir()得到一个File在你的包的根files/目录下.
要写入内部存储器子文件夹中的文件,首先需要创建文件(如果尚未存在,则需要创建子文件夹),然后创建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();
}
}
Run Code Online (Sandbox Code Playgroud)