[file-io] Groovy write to file (newline)

I created a small function that simply writes text to a file, but I am having issues making it write each piece of information to a new line. Can someone explain why it puts everything on the same line?

Here is my function:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
    File file = new File("$directory/$fileName$extension")

    infoList.each {
        file << ("${it}\n")
    }
}

The simple code I'm testing it with is something like this:

def directory = 'C:/'
def folderName = 'testFolder'
def c

def txtFileInfo = []

String a = "Today is a new day"
String b = "Tomorrow is the future"
String d = "Yesterday is the past"

txtFileInfo << a
txtFileInfo << b
txtFileInfo << d

c = createFolder(directory, folderName) //this simply creates a folder to drop the txt file in

writeToFile(c, "garbage", ".txt", txtFileInfo)

The above creates a text file in that folder and the contents of the text file look like this:

Today is a new dayTomorrow is the futureYesterday is the past

As you can see, the text is all bunched together instead of separated on a new line per text. I assume it has something to do with how I am adding it into my list?

This question is related to file-io groovy

The answer is


Might be cleaner to use PrintWriter and its method println.
Just make sure you close the writer when you're done


I came across this question and inspired by other contributors. I need to append some content to a file once per line. Here is what I did.

class Doh {
   def ln = System.getProperty('line.separator')
   File file //assume it's initialized 

   void append(String content) {
       file << "$content$ln"
   }
}

Pretty neat I think :)


@Comment for ID:14. It's for me rather easier to write:

out.append it

instead of

out.println it

println did on my machine only write the first file of the ArrayList, with append I get the whole List written into the file.

Kindly anyway for the quick-and-dirty-solution.


As @Steven points out, a better way would be:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
  new File("$directory/$fileName$extension").withWriter { out ->
    infoList.each {
      out.println it
    }
  }
}

As this handles the line separator for you, and handles closing the writer as well

(and doesn't open and close the file each time you write a line, which could be slow in your original version)