gpt4 book ai didi

java - 逐行写入文件

转载 作者:行者123 更新时间:2023-11-30 06:52:18 25 4
gpt4 key购买 nike

我正在一个目录中编写一组文件。这是我的代码,

String directoryName = "logs";
File directory = new File(String.valueOf(directoryName));
if (!directory.exists()) {
directory.mkdir();
}

System.out.println("Simulating logs....");
for (int i = 0; i < 1440; i++) {

long now = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1);

String fileName = now + ".txt";
Path filePath = Paths.get(directoryName, fileName);

LogGenerator generator = new LogGenerator(noOfServers);
Set<String> logs = generator.generateLog();
try {
Files.write(filePath, logs, Charset.forName("US-ASCII"));
} catch (IOException e) {
e.printStackTrace();
}

}

问题是,设置日志的所有元素都附加在第一个元素之后并写在同一行中。这发生在这一行,

Files.write(filePath, logs, Charset.forName("US-ASCII"));

我想在一个新行中写集合的每个元素。我怎样才能做到这一点?

最佳答案

这是 javadoc 的内容说到write方法:

"Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset."

我假设该方法执行 javadoc 明确说明的操作。以下是一些可能的替代解释:

  • 这些行由 generateLog() 方法连接。
  • Java 对平台行分隔符的理解(在运行代码的机器上)与您用来查看文件的应用所期望的不匹配。
  • 您在未呈现原始行分隔符的上下文中查看输出;例如一个 HTML 文档 ...

关于java - 逐行写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39133789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com