繁体   English   中英

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

[英]Avoid extra new line, writing on .txt file

目前我正在使用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"));

在此处输入图片说明

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

1 | 1. Hello
2 | 2. I am Fine
3 | 3. What about U ?
4 |

检查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;
    }

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

writer.newLine(); 

解决方案是:以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")));

来自 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);

我会做

Files.writeString(filePath, String.join("\n",lineList), Charset.forName("UTF-8"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM