编写使用Groovy(Grails的),以文件失败对于一些线(虚线) [英] Writing to file with Groovy(Grails) fails for some lines (broken lines)
问题描述
我在.csv文件中使用Groovy进行一些大规模的写作。更具体地讲,我有一个正在运行,并创建一个被发送到RabbitMQ的队列地图的一些消息的石英工作。队列正在由10名消费者,并导致生产串的某些列表耗尽。对于列表中的每个元素我只是把它写在管道分隔.csv文件。有一个写入.csv文件中的方法的实际服务,是一个标准的(单)交易Grails的服务。当我登录要写入的线条,一切都很好,但在文件中,一些线破。我写的方法是:
I am performing some mass writing in a .csv file using Groovy. More specifically, I have a Quartz job that is running and creates some Map messages that get sent to a RabbitMQ queue. The queue is being consumed by 10 consumers and results in producing some lists of Strings. For each element in the List I just write it in a pipe separated .csv file. The actual service that has the method that writes to the .csv file, is a standard (singleton) transactional grails service. When I log the lines to be written, everything's fine, but in the file, some lines are "broken". The way I am writing is:
def writeRowsToFile(List<String> rows, File file) {
rows.each {row->
file.append("${row}\n")
}
}
起初我是用:
file.withWriterAppend {out->
out.write(row.toString())
out.newLine()
}
和得到了同样的事情,以及...
and got the same thing as well...
如果这是一件错了,它会失败的所有行。难道是某种竞争条件,并发或我不知道还有什么问题?
If it was something wrong it would fail for all the lines. Could it be some kind of race condition, concurrency or I don't know what else issue?
任何帮助将AP preciated。
Any help will be appreciated.
感谢
推荐答案
您应该做的是第二种方式,即:
You should be doing it the second way, ie:
def writeRowsToFile(List<String> rows, File file) {
file.withWriterAppend {out->
rows.eachWithIndex { row, idx ->
// It's probably \n chars in your strings
if( row ==~ /.*[\n\r]+.*/ ) {
println "Detected a CRLF char in rows[$idx]"
}
out.writeLine row
}
}
}
不过,你说这可能是某种竞争状态
However, you say it might be "some kind of race condition"
多个线程写入同一个文件?
Are multiple threads writing to the same file?
如果不是,它更可能是你的行
数据具有 \\ n
内的字符
If not, it is more likely that your row
data has \n
characters in it
这篇关于编写使用Groovy(Grails的),以文件失败对于一些线(虚线)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!