Android如何检查文件是否存在,否则创建一个?

时间:2011-06-25 08:04:22

标签: android file

我有以下问题。我想将名为data.xml的文件放入sdcard / appname文件夹,并将其用于读写应用程序数据。

因此,当我的主要活动创建时,我需要检查此文件是否存在:

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);
      }

但是我在最后一行中有Unhandled异常类型FileNotFoundException。有什么问题?使用权限WRITE_EXTERNAL_STORAGE被添加到清单。

2 个答案:

答案 0 :(得分:4)

不要硬编码SDCard文件路径。对于不同的设备和API,它可能会有所不同。

例如它为Froyo而/mnt/sdcard/,而我的Galaxy Nexus(JellyBean)的/storage/sdcard0/Environment.getExternalStorageDirectory()

Android Developer's Guide建议使用// Some Code String path = Environment.getExternalStorageDirectory().getPath() + "/appname/"; File file = getBaseContext().getFileStreamPath(path); // More Code

尝试这样做:

{{1}}

答案 1 :(得分:2)

路径'/ sdcard / appname'是否存在?在检查子目录“appname”之前检查文件。在尝试访问其中的文件之前,您需要检查是否存在。

此外,如果您只是需要该文件来读写应用程序数据,为什么不只是使用内部存储 - 少一个明显的权限:) - > read here for internal storage