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?
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.
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.
Thanks so much! Groovy handles the close for you. So no need to explicitly call it.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With