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

时间:2017-05-14 06:40:13

标签: java nio

目前我正在使用for item in range(len(shape_brightness)): execute 来编写txt文件。代码就在这里......

java.nio.file.File.write(Path, Iterable, Charset)

enter image description here

但是在文本文件中生成了另外一个(第4个)空行。我怎样才能避免第4条空行?

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

3 个答案:

答案 0 :(得分:4)

从javadoc for write:&#34;每一行都是一个char序列,按顺序写入文件,每行由平台的行分隔符终止,由系统属性line.separator。&#34;

最简单的方法:

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

答案 1 :(得分:2)

检查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")));

答案 2 :(得分:0)

我愿意

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