0

I have a simple class that loads a .yaml file from the package, replaces some string, then writes the new file to some location. I am aware of the proposed solution to use REGEX: .replaceFirst("[\n\r]+$", ""); but my problem is not replacing a trailing newline from a String...

For example, from my code below, printing lines results in:

[fileName: myFileName, instance: instance, database: database] // no trailing \n

Although there is no trailing \n in lines, I see one in my newly generated build.yaml file. I'm looking for a way to remove this trailing newline from my new file.

Java class:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test {
    public static void main(String[] args) {
        new Test("myPath", "myFileName");
    }

    public Test(String path, String filename) {
        File f = new File(path);

        InputStream is = Test.class.getResourceAsStream("build.yaml");

        try (Stream<String> lines = new BufferedReader(new InputStreamReader(is)).lines()) {

            List<String> replaced = lines
                    .map(line -> line.replace("##FILENAME##", filename))
                    .collect(Collectors.toList());

            Files.write(Paths.get(f.getAbsolutePath()), replaced);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Resource in package (build.yaml):

fileName: ##FILENAME##
instance: instance
database: database

Output (build.yaml):

fileName: myFileName
instance: instance
database: database
// there is a newline here!

Desired Output (build.yaml):

fileName: myFileName
instance: instance
database: database
sleepToken
  • 1,866
  • 1
  • 14
  • 23
  • 1
    See https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline - what's the actual problem with the trailing newline? Does it cause any errors down the line? – Clashsoft Mar 02 '20 at 17:30
  • 2
    The trailing newline is part of the implementation of [`Files.write`](https://github.com/openjdk/jdk/blob/e455d382e79fe3ee15e434cda125b7206bf70bd5/src/java.base/share/classes/java/nio/file/Files.java#L3560). – omajid Mar 02 '20 at 17:31
  • If you want to operate on lines, you have to live with that. Otherwise, switch to reading the whole file as a String, do the replacement on that, and then write it back to the file. – Clashsoft Mar 02 '20 at 17:32
  • I was afraid of this. This trailing line causes a Jenkins build to blow up... but I don't control that code. So I guess I can close this. – sleepToken Mar 02 '20 at 17:33
  • 1
    Does this answer your question? [Avoid extra new line, writing on .txt file](https://stackoverflow.com/questions/43961095/avoid-extra-new-line-writing-on-txt-file) – vicpermir Mar 02 '20 at 17:34

0 Answers0