机器人如何检查文件是否存在,否则创建一个? [英] Android how to check if file exist and else create one?

查看:114
本文介绍了机器人如何检查文件是否存在,否则创建一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题。我想放置一个名为data.xml的到SD卡/应用程序的名字的文件夹,并用它来读取和写入应用程序数据。

I have following question. I'd like to place a file named data.xml into sdcard/appname folder and use it for read and write application data.

所以,当我的主要活动创建我需要检查,如果该文件存在:

So, when my main activity creates I need to check if this file exist:

public class appname extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(R.layout.no_elements_l);

      File file = getBaseContext().getFileStreamPath("/sdcard/appname/data.xml");
      if(file.exists()) { 

            return;

      } else {

            // create a File object for the parent directory
            File MTdirectory = new File("/sdcard/appname/");

            // have the object build the directory structure, if needed.
            MTdirectory.mkdirs();

            // create a File object for the output file
            File outputFile = new File(MTdirectory, "data.xml");

            // now attach the OutputStream to the file object, instead of a String representation
            FileOutputStream DataFile = new FileOutputStream(outputFile);
      }

但我在最后一行未处理的异常类型FileNotFoundException异常。什么问题?用途许可WRITE_EXTERNAL_STORAG​​E添加到体现。

But I have Unhandled exception type FileNotFoundException in last line. What's the problem? Uses permission WRITE_EXTERNAL_STORAGE is added to manifest.

推荐答案

请问路径/ SD卡/应用程序的名字'存在吗?您检查的文件,你检查的子目录应用程序的名字'之前。您需要检查是否存在您试图访问一个文件里面了。

Does the path '/sdcard/appname' exist? You check for the file before you check for the sub-directory 'appname'. You need to check if that exists before you try to access a file inside it.

此外,如果你只需要在文件读写的应用程序的数据,为什么不只是去与内部存储 - 少了一个明显的权限:) - >的这里的内部存储读取

Also if you simply need the file to read-write application data why not just go with internal storage - one less manifest permission :) -> read here for internal storage

这篇关于机器人如何检查文件是否存在,否则创建一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆