避免在.txt文件上写多余的新行 [英] Avoid extra new line, writing on .txt file

查看:74
本文介绍了避免在.txt文件上写多余的新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Currently I am using java.nio.file.File.write(Path, Iterable, Charset) to write txt file. Code is here...

    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个)空行.如何避免第四个空行?

But one more (4th) empty line generated in the text file. How can I avoid 4th empty line ?

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

推荐答案

从javadoc进行写入:每行都是一个char序列,并按顺序写入文件,每行由平台的行分隔符终止,由系统属性line.separator定义."

From javadoc for write: "Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator."

您想要做的最简单的方法:

Simplest way to do as you wish:

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

这篇关于避免在.txt文件上写多余的新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆