避免额外的新行,写入 .txt 文件

Mr.*_*Mak 3 java nio

目前我正在使用java.nio.file.File.write(Path, Iterable, Charset)编写txt文件。代码在这里...

    Path filePath = Paths.get("d:\\myFile.txt");
    List<String> lineList =Arrays.asList("1. Hello", "2. I am Fine", "3. What about U ?");
    Files.write(filePath, lineList, Charset.forName("UTF-8"));
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

但是在文本文件中又生成了一个(第 4 个)空行。如何避免第 4 个空行?

1 | 1. Hello
2 | 2. I am Fine
3 | 3. What about U ?
4 |
Run Code Online (Sandbox Code Playgroud)

Bor*_*aze 6

来自 javadoc for write:“每行都是一个字符序列,并按顺序写入文件,每行以平台的行分隔符终止,如系统属性 line.separator 所定义。”

最简单的方法,如你所愿:

List<String> lineList =Arrays.asList("1. Hello", "2. I am Fine");
String lastLine = "3. What about U ?"; 
Files.write(filePath, lineList, Charset.forName("UTF-8"));
Files.write(filePath, lastLine.getBytes("UTF-8"), StandardOpenOption.APPEND);
Run Code Online (Sandbox Code Playgroud)

  • 哎呀...我忘了添加打开选项。固定的。 (2认同)

Max*_*tin 5

检查Files.write您调用的代码:

public static Path write(Path path, Iterable<? extends CharSequence> lines,
                             Charset cs, OpenOption... options)
        throws IOException
    {
        // ensure lines is not null before opening file
        Objects.requireNonNull(lines);
        CharsetEncoder encoder = cs.newEncoder();
        OutputStream out = newOutputStream(path, options);
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) {
            for (CharSequence line: lines) {
                writer.append(line);
                writer.newLine(); 
            }
        }
        return path;
    }
Run Code Online (Sandbox Code Playgroud)

它在每个插入的末尾创建新行:

writer.newLine(); 
Run Code Online (Sandbox Code Playgroud)

解决方案是:提供数据为byte[]

Path filePath = Paths.get("/Users/maxim/Appsflyer/projects/DEMOS/myFile.txt");
List<String> lineList =Arrays.asList("1. Hello", "2. I am Fine", "3. What about U ?");
String lineListStr = String.join("\n", lineList);
Files.write(filePath, lineListStr.getBytes(Charset.forName("UTF-8")));
Run Code Online (Sandbox Code Playgroud)