0

我正在尝试制作一个程序,将字符串列表保存到文件中,然后将它们读入arraylist。这是我当前的代码。

ObjectInputStream input = null;

    try {
        input = new ObjectInputStream(new FileInputStream("friends.txt"));
    } catch (FileNotFoundException e) {
        File f = new File("friends.txt");
        try {
            f.createNewFile();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String obj;

    try {
        while ((obj = (String)input.readObject()) != null) {
            friendly.add(obj);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

这将返回一个空指针异常。我不太确定这里出了什么问题。

4

1 回答 1

2

好吧,一方面,如果文件不存在,“输入”将为空。

我不太确定以您的方式处理文件不存在的情况的基本原理是什么 - 为什么不只是通过 File.exists() 测试存在,并且只在存在时执行打开和读取?

除此之外,正如另一位评论员所说,提供一个堆栈跟踪作为开始。

于 2012-05-16T01:36:00.443 回答