Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

java - Directory & File Creation on Android File System

I'm trying to create a directory hierarchy and then copy a file from my assets into the newly created directory. I've used the code samples offered here on stackoverflow but I'm not getting anywhere. Essentially my code goes like this:

InputStream in = getAssets.open(mydb.sqlite);
File dir = new File("/data/data/my.package/databases/");

dir.mkdirs();
out = new FileOutputStream("/data/data/my.package/databases/mydb.sqlite");
while ((len = in.read(buffer)) > 0)
{
    out.write(buffer, 0, len);
}
out.flush();
out.close();
in.close

This is all done within the main activity on first launch and of course should only be done once. Before the code runs, the only directory that exists is /data/. Yes, it is a database file but that shouldn't matter at this point since I'm just copying the file and haven't yet tried to access it with the database code.

The code doesn't throw any exceptions, and dir.mkdirs() returns true. Regardless, the directories are not created and the file is not copied. I have added the permissions line for WRITE_EXTERNAL_STORAGE to my manifest as has been suggested in several places, FWIW. I can step through the code and everything appears to be fine. But of course it's not.

What do I need to be looking for here? File permissions problems? Why does the code think everything is there (ie, when it gets to the copy code, it doesn't throw FileNotFoundException) but in reality there's nothing on the file system?

Edit: Here's what I've learned. getDir() creates the directory in /data/data/my.package/app_*. Not sure why it uses this prefix on the directory name. This won't work if you need to put something in a standard location such as databases/ or files/.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use openFileOutput instead as /data/data is internal storage and you should only use the Android APIs to get a file handle there. See: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Edit: /data/data/my.package is handled by openFileOutput/getDir so you would create your directory with getDir('databases',MODE_PRIVATE) and create your file there.

Edit2: From getDir documentation:

You can use the returned File object to create and access files in this directory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...