Avoid extra new line, writing on .txt file

生来就可爱ヽ(ⅴ<●) 提交于 2020-05-08 14:43:45

问题


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

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 |

回答1:


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



回答2:


Check Files.write the code you call:

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

It creates new line at the end of each insert:

writer.newLine(); 

The solution is: provide data as 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")));



回答3:


I would do

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


来源:https://stackoverflow.com/questions/43961095/avoid-extra-new-line-writing-on-txt-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!