Writing to a new line in a file using Commons IO?

I know that

FileUtils.writeStringToFile(myfile.txt, "my string", true);

adds 'my line' to the end of myfile.txt, so it looks like

previous stringsmy string

But is there a way to use Commons IO to write a line to a new line in a file, to change the file to

previous strings
my string
+4
source share
3 answers

Java uses \nto indicate a new line, so try:

FileUtils.writeStringToFile(myfile.txt, "\nmy string", true);
+6
source

announce

final String newLine = System.getProperty("line.separator");

and in a call FileUtils.writeStringToFile(myfile.txt, yourVariable+newLine, true);

I use a variable, so for me it was more useful

+3
source

In addition to the above answer;

If you do not have a huge file, you can write:

List<String> lines = Files.readAllLines(Paths.get(myfile.txt), StandardCharsets.UTF_8);
lines.add("my string");
Files.write(Paths.get(myfile.txt), lines, StandardCharsets.UTF_8);  

It is usually useful to add a new line in the middle of the file.

List<String> lines = Files.readAllLines(Paths.get(myfile.txt)), StandardCharsets.UTF_8);
lines.add(6, "my string"); // for example
Files.write(Paths.get(myfile.txt), lines, StandardCharsets.UTF_8); 
+1
source

All Articles