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

编程入门 行业动态 更新时间:2024-10-26 16:35:19
本文介绍了机器人如何检查文件是否存在,否则创建一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下问题。我想放置一个名为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

更多推荐

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

本文发布于:2023-11-06 21:49:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564772.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:创建一个   机器人   是否存在   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!