java - 将序列化对象写入文件

标签 java android android-studio object saving-data

我在将 Java 对象保存到文件 时遇到问题。我正在使用 Android Studio 编写应用程序。

Outgoing是我要保存的对象,它包含两个String,一个int

private FileOutputStream fileOutputStream;
private ObjectOutputStream objectOutputStream;

public void save(String name, String category, int price){

    // Open file
    try {
        fileOutputStream = new FileOutputStream("outgoings.tmp");
        objectOutputStream = new ObjectOutputStream(fileOutputStream);
    } catch (IOException ioException) {
        System.err.println(ioException.getMessage());
    }

    // Saving
    Outgoing record;
    Scanner input = new Scanner(System.in);

    while (input.hasNext()) {
        try{
            if(name != null){
                record = new Outgoing(name, category, price);
                objectOutputStream.writeObject(record);
            }
        }
        catch(IOException ioException){
            System.err.println(ioException.getMessage());
        }
    }

    // Close file
    try{
        objectOutputStream.close();
    }
    catch (IOException ioException) {
        System.err.println(ioException.getMessage());
    }
}

当我启动应用程序时,执行方法save(),应用程序崩溃了。

// Open file
try {
    fileOutputStream = new FileOutputStream("outgoings.tmp");
    objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException ioException) {
    System.err.println(ioException.getMessage());
}

--> 抛出 IOException 并且 Logcat 向我显示:

Logcat

合适的文件路径是什么?我应该使用哪种数据类型?

感谢您的帮助

最佳答案

如果您收到消息 “打开文件时出错。”,这意味着对 openFile() 的调用失败了:

public void openFile() {
    try {
        fileOutputStream = new FileOutputStream("outgoings.tmp");
        objectOutputStream = new ObjectOutputStream(fileOutputStream);
    } catch (IOException ioException) {
        System.err.println("Error opening file.");
    }

ObjectOutputStream 构造函数在这种情况下几乎不会失败,所以问题一定是 new FileOutputStream("outgoings.tmp") 抛出了 IOException,最可能的解释是您没有在当前目录中创建文件的权限。 (其他解释也是可能的....)

要深入了解这一点,您需要修改代码以打印或记录 IOException 的堆栈跟踪。


关于这个“初学者”代码还应该说明的其他几点。

  1. 这样做是个坏主意:

    } catch (IOException ioException) {
        System.err.println("Error opening file.");
    }
    

    为什么?因为在报错之后,你是在告诉代码继续,就好像什么事都没发生过一样。接下来您将尝试使用 objectOutputStream ……它还没有被初始化!

    您应该构建代码,以便您不会应该被代码视为 fatal error 之后继续。

  2. 如果您在可能会重复打开文件的实际程序中执行此操作,那么您很可能会泄露文件描述符。打开和使用文件的正确模式(对于 Java 6 及更高版本)是使用“try-with-resources”结构;例如

    try (FileOutputStream out = new FileOutputStream(...)) {
        // write stuff
    }
    

    try 的主体结束时,开始时打开的资源将自动关闭。这在所有重要的情况下都会发生。相比之下,如果您手动关闭资源,则存在无法在所有情况下全部关闭的风险。

关于java - 将序列化对象写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48826928/

相关文章:

java - java中String的垃圾回收

android - 在应用程序中离线使用谷歌地图

android - 在 Android Studio 中显示 Cordova "console.log"条目

android - Android Studio 中的 "Subversion command line client version is too old"错误

java - 无法在 Android Studio 中访问我的小部件

android - Users\[username] 目录下的两个 .AndroidStudio 文件夹

java - 处理数组时如何同时使用 Java 和 Groovy 语法?

java - @Async 在 Spring Boot 应用程序中给我错误

java - 顺序拆分器上的 estimateSize()

java - 每次加载图像时堆都会增长