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

16,072

Solution 1

Java use \n to mark new line so try with:

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

Solution 2

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

Solution 3

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); 
Share:
16,072
Chris Schmitz
Author by

Chris Schmitz

I'm a Data Science MSc student, and work in AI consultancy.

Updated on June 04, 2022

Comments

  • Chris Schmitz
    Chris Schmitz almost 2 years

    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
    
  • cnmuc
    cnmuc over 9 years
    Would put the \n to the end of the string. Otherwise the file starts with an empty row. Like this: FileUtils.writeStringToFile(myfile.txt, "my string\n", true);
  • user987339
    user987339 over 9 years
    I agree with your comment, but this was a special case.
  • akshit bhatia
    akshit bhatia over 4 years
    For me, a new file is made every time, a new string is appended... Any reason for that? This is my code: File file=new File("/Users/akshitbhatia/Documents/workspace/SNLP/src/miniP‌​roject/output.txt"); for(int i=1;i<3;i++){ String result="\n"+P1+factToken[0]+P2+value+P3+"\t."; FileUtils.writeStringToFile(file, result, "UTF-8"); }
  • user987339
    user987339 over 4 years
    @akshitbhatia Instead of FileUtils.writeStringToFile(file, result, "UTF-8") use FileUtils.writeStringToFile(file, result, "UTF-8", true) which will append to existing file.