使用 Groovy(Grails) 写入文件对于某些行(断行)失败 [英] Writing to file with Groovy(Grails) fails for some lines (broken lines)

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

问题描述

我正在使用 Groovy 在 .csv 文件中执行一些大规模写入.更具体地说,我有一个正在运行的 Quartz 作业,并创建了一些发送到 RabbitMQ 队列的 Map 消息.队列被 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}
")
  }
}

最初我使用的是:

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?

任何帮助将不胜感激.

谢谢

推荐答案

你应该用第二种方式,即:

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 
 chars in your strings
      if( row ==~ /.*[

]+.*/ ) {
        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?

如果不是,您的 row 数据中更有可能包含 个字符

If not, it is more likely that your row data has characters in it

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

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