Reputation: 658
I know that
FileUtils.writeStringToFile(myfile.txt, "my string", true);
adds 'my string' to the end of myfile.txt, so it looks like
previous stringsmy string
But is there any way to use Commons IO to write a string to a new line in a file, to change the file to
previous strings
my string
Upvotes: 7
Views: 19772
Reputation: 2373
declare
final String newLine = System.getProperty("line.separator");
and in call, FileUtils.writeStringToFile(myfile.txt, yourVariable+newLine, true);
i use a variable , so this was more useful for me
Upvotes: 4
Reputation: 77910
In addition to above mentioned response;
If you doesn't have 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);
Generally its good to add new row in the middle of 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);
Upvotes: 2
Reputation: 10717
Java use \n
to mark new line so try with:
FileUtils.writeStringToFile(myfile.txt, "\nmy string", true);
Upvotes: 8