【发布时间】:2015-07-16 21:33:55
【问题描述】:
我需要将一些数据保存到文本文件中。我正在使用类Files 及其方法write()。
如果这样的文件不存在 - 一切都好。问题是如果这样的文件已经存在,它会将新数据附加到文件的末尾。我需要先清除它。代码是:
public static void main(String[] args) {
DepoList test0 = new DepoList();
test0.init();
ArrayList<Depo> list0 = test0.getList();
Collections.sort(list0);
for (Depo depo : list0) {
String str = String.format("sum = %1$8.2f interest = %2$7.2f\n", depo.getSum(), depo.getIncome());
System.out.format(str);
try {
Files.write(Paths.get("depo.txt"), str.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println();
我想我需要再添加一些StandardOpenOperation。如何在放数据之前清除文件?
【问题讨论】:
-
是的。否则,它会创建最后一个字符串的文件。
-
你看过其他
StandardOpenOptions 吗?似乎有明显的选择......