Groovy写入文件(换行符) [英] Groovy write to file (newline)

查看:1549
本文介绍了Groovy写入文件(换行符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的将文本写入文件的小函数,但是我遇到了一些问题,使得它将每条信息写入一个新行。有人可以解释为什么它把所有的东西放在同一条线上?



以下是我的函数:

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

infoList.each {
file< < ($ {it} \\\

}
}

我正在测试它的简单的代码是这样的:
$ b $ pre $ def $目录='C:/'
def folderName ='testFolder'
def c
$ b $ def txtFileInfo = []

String a =今天是新的一天
String b = 明天是未来
String d =昨天是过去

txtFileInfo<<
txtFileInfo<< b
txtFileInfo<< d

c = createFolder(directory,folderName)//这个简单的创建一个文件夹来删除
$ b中的txt文件writeToFile(c,garbage,.txt, txtFileInfo)

上面在该文件夹中创建了一个文本文件,文本文件的内容如下所示:

 今天是新的一天明天是未来昨天是过去的

正如您所看到的那样,文本全部聚拢在一起,而不是按每个文本的新行分隔。我认为这与我如何将它添加到我的列表中有关系?

解决方案

它看起来像我,重新在窗口中工作,在这种情况下,不是简单的 \\\
,而是 \r\\\



您可以通过 System.getProperty(line.separator)获取正确的换行符例如。

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?

解决方案

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.

这篇关于Groovy写入文件(换行符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆