本文介绍了对于某些行(断行),使用 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}\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?

任何帮助将不胜感激.

谢谢

推荐答案

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

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?

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

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

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

08-01 06:52