我有以下问题。我想放置一个名为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_STORAGE添加到体现。
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
更多推荐
机器人如何检查文件是否存在,否则创建一个?
发布评论