2

如何\n使用Unix 选择行尾java.nio.file.Files.write?可能吗?我没有找到任何要选择的选项或常量。这是我的方法

import java.io.File;
//...
public void saveToFile(String absolutePath) {
        File file = new File(path); 
        try {
            Files.write(file.toPath(), lines/*List<String>*/, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
4

2 回答 2

1

BufferedWriter除了打开文件并手动写入之外,您别无选择:

try (
    final BufferedWriter writer = Files.newBufferedWriter(file.toPath(),
        StandardCharsets.UTF_8, StandardOpenOption.APPEND);
) {
    for (final String line: lines) {
        writer.write(line);
        writer.write('\n');
    }
    // Not compulsory, but...
    writer.flush();
}

(或者你按照@SubOptimal 所说的那样做;你的选择!)

于 2015-01-05T11:21:01.873 回答
1

您可以覆盖该line.separator属性

System.setProperty("line.separator", "\n");

PRO:您也Files.write(...可以在非 UNIX 环境中使用 UNIX lineends
CON:更改此属性很可能会产生意想不到的副作用

或者你在一个循环中写下这些行。

于 2015-01-05T11:22:16.423 回答