gpt4 book ai didi

java - 在java中创建文本文件并以unix格式保存

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:18:33 27 4
gpt4 key购买 nike

我需要编写java代码才能在Unix环境下进行文件操作。由于需要处理文件,如何在Java中创建并保存Unix格式的文件?

最佳答案

“Unix 格式”只是一个表示 line endings 的文本文件使用 \n 而不是 \n\r (Windows) 或 \r (OSX 之前的 Mac)。

这是基本思想;编写每一行,然后是显式 \n(而不是依赖于平台的 .newLine()):

public static void writeText(String[] text){
Path file = Paths.get("/tmp/filename");
try (BufferedWriter bw = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
for(String s : text){
bw.write(s);
bw.write("\n");
}
} catch (IOException e) {
System.err.println("Failed to write to "+file);
}
}

关于java - 在java中创建文本文件并以unix格式保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11530796/

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