如何只将日期写入文本文件一次?

问题描述 投票:0回答:2

我成功创建了一个文件并写了一个日期,但是当我运行我的应用程序时,每次都会覆盖当前日期。

我想做的事:

  1. 应用程序第一次运行时,在项目目录中创建一个文件
  2. 将当前日期写入文件
  3. 如果我再次运行程序并且有文本(日期),则读取当前日期并显示它System.out.println()

我的代码有什么问题?

public class Main {

public static void main(String[] args) throws IOException{

Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
String date = dateFormat.format(currentDate);

File file = new File("outTest.txt");
FileWriter writer = new FileWriter(file);


FileReader fr = new FileReader("outTest.txt");
BufferedReader br = new BufferedReader(fr);
String str;

if (file.length() == 0) {

      writer.write(date);
      writer.flush();
      writer.close();

}
else if(file.length() > 0) {

  while ((str = br.readLine()) != null) {
    System.out.println(str + "\n");
  }
  br.close();

}

}

}
java
2个回答
2
投票

您可以使用Java NIO:

LocalDateTime currentDate = LocalDateTime.now();
String date = DateTimeFormatter.ofPattern("HH:mm").format(currentDate);

Path file = Paths.get("outTest.txt");

if (!Files.exists(file) || Files.size(file) == 0) {
    Files.write(file, List.of(date));
}

Files.lines(file).forEach(System.out::println);

编辑:使用java.time和UTF-8字符集。

编辑2:不需要显式字符集参数,因为NIO默认使用UTF-8


0
投票

检查文件exists然后打印:

// test to see if a file exists
File file = new File("filename-date.txt");
exists = file.exists();
if (file.exists() && file.isFile())
{
  System.out.println("File exists. Here is the name: " + file.getName());
}
© www.soinside.com 2019 - 2024. All rights reserved.