Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy write to file (newline)

Tags:

file-io

groovy

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?

like image 414
StartingGroovy Avatar asked Nov 24 '10 22:11

StartingGroovy


People also ask

How do you make a new line in Groovy?

Some systems require \n and others require \r\n. It's hard to tell, so let the system figure it out as per this example.

How do I write a print statement in Groovy?

You can use the print function to print a string to the screen. You can include \n to embed a newline character. There is no need for semi-colon ; at the end of the statement. Alternatively you can use the println function that will automatically append a newline to the end of the output.

How do you close a Groovy file?

Thanks so much! Groovy handles the close for you. So no need to explicitly call it.


2 Answers

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)

like image 56
tim_yates Avatar answered Sep 21 '22 16:09

tim_yates


It looks to me, like you're working in windows in which case a new line character in not simply \n but rather \r\n

You can always get the correct new line character through System.getProperty("line.separator") for example.

like image 23
mfloryan Avatar answered Sep 20 '22 16:09

mfloryan