简体   繁体   English

覆盖我的应用程序中的文件

[英]Overwrite file in my app

When I start the application I will invoke a web service and save a file returned by the service in my app. 启动应用程序时,我将调用Web服务并将该服务返回的文件保存在我的应用程序中。 For offline purposes i want to have a file in my app, in case the web service is down. 为了离线目的,我希望在我的应用程序中有一个文件,以防Web服务关闭。

My question is: I want to overwrite the file i have, with the file I received from the web service. 我的问题是:我想用从Web服务收到的文件覆盖我拥有的文件。 How should i do this? 我应该怎么做? Where should i save the files to be able to perform this task? 我应该在哪里保存文件以执行此任务?

I was saving the file received in my internal storage, but the offline file I don´t know where i should save it. 我将收到的文件保存在内部存储器中,但是我不知道该脱机文件应该保存在哪里。 Any code? 有代码吗? Indications? 适应症? New to this. 这是新手。

I would suggest: 我会建议:

  • Keep your file inside of your project (APK) 将文件保存在项目中(APK)
  • On first start, copy this file to local storage 首次启动时,将此文件复制到本地存储
  • On successful web API return, copy (and overwrite) the file on local storage. 成功返回Web API后,复制(并覆盖)本地存储上的文件。
  • Always read from the file on local storage 始终从本地存储中的文件读取

You should save files in your application's internal storage directory by using getExternalStorageDirectory which will put your files in this location: /Android/data/<package_name>/files/ . 您应该使用getExternalStorageDirectory将文件保存在应用程序的内部存储目录中,该文件会将文件放置在以下位置: /Android/data/<package_name>/files/ This is the best location to put files because when your application is uninstalled, the files in this directory will also be removed. 这是放置文件的最佳位置,因为在卸载应用程序时,此目录中的文件也将被删除。

More info see: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal and http://developer.android.com/training/basics/data-storage/files.html 有关更多信息,请参见: http : //developer.android.com/guide/topics/data/data-storage.html#filesExternalhttp://developer.android.com/training/basics/data-storage/files.html

There are basically two locations in android you can use to save files. android中基本上有两个位置可以用来保存文件。 The external storage accessible to the user and all the applications, or the private directory dedicated to your app. 用户和所有应用程序可以访问的外部存储,或应用程序专用的私有目录。 For your purpose the later seems more appropriate. 为了您的目的,以后似乎更合适。

For manipulating files in your private storage see the openFileInput and openFileOutput (and other) methods in the Context class. 有关在私有存储中操作文件的信息,请参见Context类中的openFileInputopenFileOutput (及其他)方法。

Save example: 保存示例:

FileOutputStream fos = context.openFileOutput("my-file", Context.MODE_PRIVATE);
fos.write(bytes);
fos.close();

Load example: 加载示例:

File f = new File(context.getFilesDir(),"my-file");
if (f.exists()) {
    byte[] bytes = new byte[(int)f.length()];
    FileInputStream fis = context.openFileInput(f.getName());
    fis.read(bytes);
    fis.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM