我需要编写java代码才能在Unix环境中进行文件操作。由于我需要处理文件,如何在Java中以Unix格式创建和保存文件?
答案 0 :(得分:4)
“Unix格式”只是一个文本文件,表示line endings \n
而不是\n\r
(Windows)或\r
(Mac 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);
}
}
答案 1 :(得分:1)