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