优化这段代码public class DataIO { public static void savePersonList(List<Person> list, String fileName) throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName)); oos.writeObject(list); oos.close(); } public static List<Person> loadPersonList(String fileName) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName)); List<Person> list = (List<Person>) ois.readObject(); ois.close(); return list; } }使其能够输出保存成功,保存失败,读入成功,读入失败的System
时间: 2024-02-03 15:04:05 浏览: 71
可以在方法中添加try-catch语句,捕获异常并输出对应的信息。修改后的代码如下:
```
public class DataIO {
public static void savePersonList(List<Person> list, String fileName) {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
oos.writeObject(list);
oos.close();
System.out.println("保存成功!");
} catch (IOException e) {
System.out.println("保存失败!");
e.printStackTrace();
}
}
public static List<Person> loadPersonList(String fileName) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
List<Person> list = (List<Person>) ois.readObject();
ois.close();
System.out.println("读入成功!");
return list;
} catch (IOException | ClassNotFoundException e) {
System.out.println("读入失败!");
e.printStackTrace();
return new ArrayList<>();
}
}
}
```
这样,在保存和读取文件时,若出现异常,就会输出对应的信息。如果保存成功或读取成功,则也会输出对应的信息。
阅读全文