Copy files inside Android internal memory

对着背影说爱祢 提交于 2019-12-11 08:05:55

问题


I am writing an Android application and I need to copy 2 files into the device' s internal storage. Currently I am able to run my application after manually copying these two files under the device' s "/data/data/[my_package_name]/files" folder using DDMS. I need to put these two files into that folder(or any folder) while my application is being installed on the device. The tip here says files within the "res/raw/" directory will be deployed to the device and will be accessible through openRawResource(), but it doesn' t tell where these files will be put inside the internal memory. To summerize, I have two files in my project folder(assets, raw, any other folder) and I need to copy these two inside a path of internal memory. How can I achieve this? Do I need any permissions included to my AndroidManifest.xml?

Thank you in advance


回答1:


No big deal. There are several ways of doing this, probably shorter than this one, though.

InputStream is = AssetManager.open("somefile.txt");
File outputFile = new File(getExternalFilesDir(), "somefile.txt");
OutputStream os = new FileOutputStream(outputFile);

//Now copy is to os. I'd recommend using Apache Commons IO
org.apache.commons.io.IOUtils.copy(is, os));

And yes, you need permissions to write to SDcard (WRITE_EXTERNAL_STORAGE).

UPDATE:
Just to clarify: What the tip says is:

Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw. resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).

The files in assets folder are included in the apk, but these are read only and they are never deployed to the internal or external memory. If you need to do that you'll have to do it by yourself, as shown in the example above.



来源:https://stackoverflow.com/questions/13583820/copy-files-inside-android-internal-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!