如何在将数据放到那里之前清除文件?

时间:2015-07-16 21:33:55

标签: java io

我需要将一些数据保存到文本文件中。我正在使用类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。如何在将数据放到那里之前清除文件?

1 个答案:

答案 0 :(得分:2)

删除StandardOpenOption.CREATE,Standardoption.APPEND这只会将您的新数据附加到现有数据

使用Files.write((Paths.get("depo.txt"), str.getBytes());