【问题标题】:Create/Write files to external storage Android创建/写入文件到外部存储 Android
【发布时间】:2014-03-12 23:30:09
【问题描述】:

我正在尝试在 Android 中创建并写入外部文件。我的最低 SDK 是 14,我的目标 SDK 是 18。我在清单中的正确位置拥有 WRITE_EXTERNAL_STORAGE 权限。以下是我创建并设置要创建的文件的文件路径的部分:

    String state = Environment.getExternalStorageState();
    if(!state.equals(Environment.MEDIA_MOUNTED)) {
        textView.setText("No external storage mounted");
    } else {
        File externalDir = Environment.getExternalStorageDirectory();
        File dir = new File(externalDir.getAbsolutePath() + "/tests-folder");
        dir.mkdir();
        if(!dir.exists()) {
            Log.i(null, "Does not exist"); // This gets printed - Why?      
        }
        File textFile = new File(dir, "test.txt");
        try {
            writeTextFile(textFile, "This is a test!");
            String text = readTextFile(textFile);
            textView.setText(text);
        } catch (IOException ex){
            textView.setText("Something went wrong!" + ex.getMessage());
        }
    }

我不断收到错误消息“出了点问题!/storage/sdcard0/tests-folder/test.txt:打开失败:ENOENT(没有这样的文件或目录)。 writeTextFile() 方法是:

private void writeTextFile(File file, String text) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(file)); // When I debug, it comes up until here and then returns with the exception
    writer.write(text);
    writer.close();
}

当它到达 writeTextFile() 方法的第一行时,代码返回异常。我的猜测是文件没有被创建。打印日志行“不存在”。为什么是这样?我用手机和模拟器都试过了。我在安装和检查后尝试断开手机连接,但没有用。

如果我修改文件路径以在外部目录的根文件夹中创建文件,则会收到 EACCES Permission denied 错误。

【问题讨论】:

  • 您可以尝试使用dir.mkdirs();,如果它不存在,它将创建整个路径,而不仅仅是文件夹。
  • 我都试过了 - 没用。

标签: android


【解决方案1】:

您确定在路径中的sdcard0 之间没有遗漏/

【讨论】:

  • 没有'/' - sdcard0 是一个术语
【解决方案2】:

我知道出了什么问题——看起来这个特定的文件要么损坏了某些东西,要么触发了一些奇怪的错误。我在同一个文件夹的不同包中创建了另一个名称不同的活动,并且效果很好(代码是复制粘贴的,所以没有任何改变)。然后我删除了这个文件并重新创建了它,它运行得很好。不知道为什么会发生这种情况,但把它放在那里以防其他人将来遇到这种情况。

在此之前,我创建了一个单独的项目并输入了相同的代码并且它可以工作。所以我回来尝试做一个项目 -> 通过 Eclipse 清理,但这也没有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多