【问题标题】:Unable to create file in Android app无法在 Android 应用中创建文件
【发布时间】:2017-05-20 06:39:41
【问题描述】:

我正在制作一个 android 应用程序,我将在其中使用文件处理,但首先我需要创建它,但使用以下代码:

File logf = new File("log1.txt");
Boolean bb = logf.exists();
if(!bb)
try {
bb = logf.createNewFile();
} catch (IOException e) {
msg.setText("not able to create file.");
}

'msg' 是我用来显示错误的 TextView 对象,当我运行这个应用程序时.. 它进入 IOException e catch.. 请告诉我是我做错了什么还是什么?...除了我我的应用使用的是 Android 2.2。

【问题讨论】:

  • logcat 告诉你什么?
  • 共享清单?
  • 因为我以前的 textview 是空的,当我运行它时.. 然后它更改为“无法创建文件。”.. 这意味着它没有创建文件并进入 catch
  • 清单文件中的 WRITE_EXTERNAL_STORAGE 权限
  • WRITE_EXTERNAL_STORAGE 如果我使用外部存储是必要的,因为我只使用我的应用程序专用的内部存储。

标签: android file-handling


【解决方案1】:

在应用存储中,请尝试以下操作:

File file = new File(getFilesDir(), "file.txt");

或者如果你想附加文件名,试试这个:

File file = new File(getFilesDir() + File.separator + "file.txt");

【讨论】:

  • 我不必在它们之间使用文件分隔符吗?
  • 不需要,请看public File(File parent, String child)
【解决方案2】:

您需要提供如下文件的绝对路径。

File file = new File(/data/packagename/files/ + "log1.txt");

【讨论】:

  • 但我没有使用外部存储,我想使用内部存储
  • rust fisher's 很简单.. 但是当我们必须与应用程序共享时,你的是必要的
猜你喜欢
  • 1970-01-01
  • 2017-12-10
  • 2018-01-13
  • 2014-11-30
  • 2015-03-23
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多