如何写文件到资产文件夹或原始文件夹在安卓?

我正在处理一些应用程序,在这些应用程序中,我必须从某个 http 位置更新一些存在于资产/原始文件夹运行时中的文件。

有没有人可以帮我分享如何在资产或原始文件夹中写文件?

110380 次浏览

It cannot be done. It is impossible.

Why not update the files on the local file system instead? You can read/write files into your applications sandboxed area.

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

Other alternatives you may want to look into are Shared Perferences and using Cache Files (all described at the link above)

You cannot write data's to asset/Raw folder, since it is packed(.apk) and not expandable in size.

If your application need to download dependency files from server, you can go for APK Expansion Files provided by android (http://developer.android.com/guide/market/expansion-files.html).

Another approach for same issue may help you Read and write file in private context of application

                 String NOTE = "note.txt";
private void writeToFile() {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
NOTES, 0));


out.write("testing");
out.close();
}


catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
}
}




private void ReadFromFile()
{
try {
InputStream in = openFileInput(NOTES);
if (in != null) {
InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(tmp);
String str;
StringBuffer buf = new StringBuffer();
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
in.close();
String temp = "Not Working";
temp = buf.toString();
Toast.makeText(this, temp, Toast.LENGTH_SHORT).show();
}
} catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
}
}

You Can't write JSON file while in assets. as already described assets are read-only. But you can copy assets (json file/anything else in assets ) to local storage of mobile and then edit(write/read) from local storage. More storage options like shared Preference(for small data) and sqlite database(for large data) are available.