我有以下问题。我想将一个名为 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);
}
但我在最后一行有未处理的异常类型 FileNotFoundException 。有什么问题?使用权限 WRITE_EXTERNAL_STORAGE 添加到清单中。
不要硬编码 SDCard 文件路径。对于不同的设备和 API,它可能会有所不同。
例如它是/mnt/sdcard/
对于 Froyo,而我的 Galaxy Nexus (JellyBean) 则为/storage/sdcard0/
Android 开发者指南 http://developer.android.com/guide/topics/data/data-storage.html#filesExternal推荐使用Environment.getExternalStorageDirectory()
尝试这样做:
// Some Code
String path = Environment.getExternalStorageDirectory().getPath() + "/appname/";
File file = getBaseContext().getFileStreamPath(path);
// More Code
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)