【问题标题】:how to clear file before putting data there?如何在将数据放在那里之前清除文件?
【发布时间】: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 吗?似乎有明显的选择......

标签: java io


【解决方案1】:

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

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

【讨论】:

  • 在这种情况下,它只添加一个值sum = 43000,00 interest = 8526,02,我需要:sum = 5500,00 interest = 69,16 sum = 2500,00 interest = 75,21 sum = 12000,00 interest = 478,68 sum = 10000,00 interest = 1041,37 sum = 43000,00 interest = 8526,02
  • 写入前是否要清除文件?如果你想附加它,你会得到sum = 5500,00 interest = 69,16 sum = 2500,00 interest = 75,21 sum = 12000,00 interest = 478,68 sum = 10000,00 interest = 1041,37 sum = 43000,00 interest = 8526,02 ,如果你不附加,你只会得到最后一个字符串
  • 是的,我想在写入数据之前清除文件。该怎么做?
猜你喜欢
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-08
  • 1970-01-01
相关资源
最近更新 更多