开发者

Write file in sub-directory in Android

I'm trying to save a file in a subdirectory in Android 1.5. I can successfully create a directory using

_context.GetFileStreamPath("foo").mkdir();

(_context is the Activity where I start the execution of savi开发者_开发知识库ng the file) but then if I try to create a file in foo/ by

_context.GetFileStreamPath("foo/bar.txt");

I get a exception saying I can't have directory separator in a file name ("/").

I'm missing something of working with files in Android... I thought I could use the standard Java classes but they don't seem to work... I searched the Android documentation but I couldn't fine example and google is not helping me too...

I'm asking the wrong question (to google)...

Can you help me out with this?

Thank you!


I understood what I was missing. Java File classes works just fine, you just have to pass the absolute path where you can actually write files.

To get this "root" directory I used _context.getFilesDir(). This will give you the root of you application. With this I can create file with new File(root + "myFileName") or as Sean Owen said new File(rootDirectory, "myFileName").


You cannot use path directly, but you must make a file object about every directory. I do not understand why, but this is the way it works.

NOTE: This code makes directories, yours may not need that...

File file = context.getFilesDir();
file.mkdir();

String[] array = filePath.split("/");
for (int t = 0; t < array.length - 1; t++) {
    file = new File(file, array[t]);
    file.mkdir();
}

File f = new File(file, array[array.length - 1]);

RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f, append);


Use getDir() to get a handle on the "foo" directory as a File object, and create something like new File(fooDir, "bar.txt") from it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜