java - openFileOutput 抛出异常

标签 java android file-io android-emulator

我正在将数据写入 Android 应用程序中的 xml 文件。我查找了如何正确执行文件 IO 并发现我需要使用 openFileOutput。据我所知,我的代码没有任何问题,但它不断在我在以下代码中包含一个 try-catch 的行抛出异常:

public void writeSearchXML(ArrayList<String> searches, String file)
        throws Exception {
    // try {
    // File newxmlfile = new File(file);
    // newxmlfile.createNewFile();
    // } catch (Exception e) {
    // }
    try {
        // THE FOLLOWING LINE THROWS AN EXCEPTION EVERY TIME
        FileOutputStream out = openFileOutput(file,
                Context.MODE_WORLD_WRITEABLE);
    } catch (Exception e) {
        throw new Exception("Failing on fileoutput stream searches.");
    }
    FileOutputStream fOut = openFileOutput(file,
            Context.MODE_WORLD_READABLE);
    // we create a XmlSerializer in order to write xml data
    XmlSerializer serializer = Xml.newSerializer();
    // we set the FileOutputStream as output for the serializer, using UTF-8
    // encoding
    serializer.setOutput(fOut, "UTF-8");
    // Write <?xml declaration with encoding (if encoding not null) and
    // standalone flag (if standalone not null)
    serializer.startDocument(null, Boolean.valueOf(true));
    // set indentation option
    serializer.setFeature(
            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
    // start a tag called "root"
    serializer.startTag(null, "searches");
    for (String search : searches) {
        serializer.startTag(null, "search");
        serializer.text(search);
        serializer.endTag(null, "search");
    }
    // // i indent code just to have a view similar to xml-tree
    // serializer.startTag(null, "username");
    // serializer.text(username);
    // serializer.endTag(null, "username");
    // serializer.startTag(null, "password");
    // serializer.text(password);
    // serializer.endTag(null, "password");
    // //serializer.attribute(null, "attribute", "value");
    serializer.endTag(null, "searches");
    serializer.endDocument();
    // write xml data into the FileOutputStream
    serializer.flush();
    // finally we close the file stream
    fOut.close();
}

所有这些代码中唯一的问题就是这一行。我在互联网上进行了搜索,但无法找到解决方案。我可以做什么来解决这个问题?

更新:抛出的异常是 fileNotFound 异常。这让我相信 openFileOutput 函数实际上并不像描述中那样创建文件。在 Android 中,我可以做什么来创建文件而不使用 openFileOutput

最佳答案

我在这里找到了答案: android what is wrong with openFileOutput?

必须使用 Activity 上下文调用 openFileOutput。

关于java - openFileOutput 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4322090/

相关文章:

Java 基准测试 - 为什么第二个循环更快?

java - 使用 ProcessBuilder 运行 ImageMagick 命令

android - Android Webview中的多个文件上传

android - 展开/折叠 listView 包含复选框时的重绘效果

java - 如何在 Hibernate/JPA 中使用 xml 编写命名查询?

java - 在 Android 上存储加密 key

java - 用 Java 解析一个很大的格式不正确的文件

ios - 代号 1 iOS 上的 Unicode/emoji

c# - 使用 LINQ 从文件中读取前 10 行

使用 yGuard 与服务提供商接口(interface)混合进行 Java 混淆