【发布时间】:2017-09-11 04:49:12
【问题描述】:
我有这段代码
public void write(LinkedList<Drug> list, String file) {
try (FileOutputStream fs = new FileOutputStream(System.getProperty("user.dir") + "\\res\\" + file + ".dat"); ObjectOutputStream os = new ObjectOutputStream(fs)) {
System.out.println("Writing File...");
os.writeObject(list);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
我想要的是使用相同的方法来编写不同对象的文件,例如
LinkedList<String> temp = new LinkedList<>();
temp.add("Something");
temp.add("Something else");
write(temp, "stringlist");
我不想只做第二种方法
public void writeSomething(LinkedList<String> list, String file) {
try (FileOutputStream fs = new FileOutputStream(System.getProperty("user.dir") + "\\res\\" + file + ".dat"); ObjectOutputStream os = new ObjectOutputStream(fs)) {
System.out.println("Writing File...");
os.writeObject(list);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
仅供参考(无关):
FileNotFoundException是IOException的子类,因此您可以删除catch (FileNotFoundException e)。如果没有,并且您想要相同的逻辑,您可以使用 multi-catch 合并它们:catch (IOException | SomeOtherException e)。 -
我认为你没有得到问题
-
我的评论不是您问题的答案。这只是一个无关的评论,试图教你更好的代码。
-
@Andreas 哦,感谢您提供的信息,非常感谢!