首页 > 解决方案 > java.io.FileNotFoundException:stack.txt:打开失败:EROFS(只读文件系统)

问题描述

编辑:在跟进这两个建议时,我确定以下内容可以将字符串作为字节数组写入文件。但现在我需要弄清楚如何将 Byte 数组读回 Strings。我可以使用帮助...是否有一个 FileInputStream 组件是这个 FileOutputStream 的反向等价物?这适用于将字符串写入字节数组。

try {
    FileOutputStream fos = openFileOutput("stack.txt", Context.MODE_PRIVATE);
    for (String item : stack)
       fos.write(stack.pop().getBytes());
    fos.close();
    sb.append("The Stack is saved.\n");
    } catch (IOException e) {
         sb.append(e.toString());
    }
displayText(sb.toString());

我正在尝试将 ArrayDeque 中的字符串写入文件。我将 ArrayDeque 用作堆栈。字符串的长度不同。打开文件进行输出时出现此错误...

java.io.FileNotFoundException: stack.txt: open failed: EROFS (Read-only file system)

我想我已经看过关于这个主题的所有帖子,但没有任何帮助。我的两个代码片段是:

  1. 在 onCreate()...
root = new File(getExternalFilesDir(null), "/HTMLSpyII/");
if (!root.exists()) {
    if (!root.mkdirs()) {
        runTimeAlert("File path does not exist or\n" +
            "Unable to create path \n" + root.toString());
            }
        }
  1. 在节目中...
try {
    DataOutputStream dos = new DataOutputStream(
        new FileOutputStream("stack.txt")); // program fails here
    for (String item : stack)
        dos.writeUTF(stack.pop());
        dos.close();
        sb.append("The Stack is saved.\n");
    } catch (IOException e) {
        sb.append(e.toString());
    }
    displayText(sb.toString());

我有使用 DataInputStream 和 FileInputStream 读取它们的并行代码。我错过了一些东西。在创建文件之前是否有一些初步准备?

做一些研究我觉得问题可能是我还不熟悉使用新的应用程序特定的、持久的、内部/外部存储的要求?但我不知道,所以我正在寻找一些指导,请:)

标签: javaandroidfilenotfoundexceptionfileoutputstreamdataoutputstream

解决方案


这是该问题的完整解决方案的大纲。希望这对某人有所帮助,有时...

  1. 问题是:要使用 ArrayDeque 作为堆栈来保存字符串,并使用文件来保存和恢复堆栈。

  2. 该解决方案的关键部分是:使用 ObjectOutputStream 和 ObjectInputStream 将堆栈保存和恢复到外部存储。使用 getExternalFilesDir() 打开文件进行保存和恢复。

  3. 要打开文件以保存当前堆栈内容...

File stackRoot = new File(getExternalFilesDir(null), "/AppName/stack.dat");
    FileOutputStream fos = new FileOutputStream(stackRoot);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
  1. 要将堆栈清空到文件中...
for (String item : stack) oos.writeObject(item);
oos.close();
  1. 要打开文件以恢复保存的堆栈内容...
File stackRoot = new File(getExternalFilesDir(null), "/AppName/stack.dat");
    FileInputStream fis = new FileInputStream(stackRoot);
    ObjectInputStream ois = new ObjectInputStream(fis);
  1. 要将文件清空到堆栈中...
while (true) stack.addLast((String) ois.readObject());

推荐阅读