3

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

enter image description here

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 |
Mr. Mak
  • 837
  • 1
  • 11
  • 25
  • IMHO, it is better to have the terminating newline than to leave it out. See for example http://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline – Henry May 14 '17 at 07:14
  • I have got a good answer below. thanks. @Henry – Mr. Mak May 14 '17 at 07:36

3 Answers3

6

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);
Bor Laze
  • 2,458
  • 12
  • 20
  • 1
    Seems this generates two files and first one (with two line) replaced by last one(one line). And finally I will get a file with only one line. – Mr. Mak May 14 '17 at 07:02
  • 2
    Oops... I forget to add open option. Fixed. – Bor Laze May 14 '17 at 07:07
  • Yes ! this is, what I wanted. Thanks a lot. – Mr. Mak May 14 '17 at 07:29
  • Dear @BorLaze . Can I append 2 or more `List lineList;` one after another to my text file. Like.. `Files.write(/*1st Line List*/); Files.write(/*2nd Line List*/) Files.write(/*3rd Line List*/)` – Mr. Mak May 15 '17 at 06:07
  • 1
    @M.A.Khomeni, why not? In the same way: `Files.write(filePath, lineList1, Charset.forName("UTF-8"), StandardOpenOption.APPEND); Files.write(filePath, lineList2, Charset.forName("UTF-8"), StandardOpenOption.APPEND);` etc. – Bor Laze May 15 '17 at 06:13
5

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")));
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
1

I would do

Files.writeString(filePath, String.join("\n",lineList), Charset.forName("UTF-8"));
r .r
  • 383
  • 2
  • 9