0

我的 Grails 应用程序从数据库读取数据并将数据写入 CSV 文件。最近,它一直失败并出现以下错误:

java.io.IOException: Stream closed
        at java.io.BufferedWriter.ensureOpen(BufferedWriter.java:98)
        at java.io.BufferedWriter.write(BufferedWriter.java:203)
        at java.io.Writer.write(Writer.java:140)
        at sun.reflect.GeneratedMethodAccessor1116.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)

当我执行以下操作时发生错误(writer.write(builder.toString()):

Writer writer
String delimiter =','

Pattern p

public CsvGenerator() {
   p = Pattern.compile(delimiter)
}

public CsvGenerator(String fullPath) {
    writer = openWriter(fullPath)
    p = Pattern.compile(delimiter)
}
public CsvGenerator(String fullPath, String delimiter) {
    writer = openWriter(fullPath)
    this.delimiter = delimiter
    p = Pattern.compile(this.delimiter)
}

protected Writer openWriter(String fullPath) {
    Writer writer = new BufferedWriter(new FileWriter(fullPath))
    return writer
}

public void closeWriter() {
    if (writer !=null) {
        writer.close()
    }
}

public void writeLine(List<Object> entries) {
    log.info "${entries}"
    StringBuilder builder = new StringBuilder()
    entries.eachWithIndex { Object entry, int index ->
        builder.append(entry ==null? '': stripChars(entry.toString()))
        //writer.write(entry ==null? '': stripChars(entry.toString()))
        if (index < entries.size()-1) {
            builder.append(delimiter)
            //writer.write(delimiter)
        }
    }
    builder.append('\r\n')
    writer.write(builder.toString())
}

private String stripChars(String s) {
    String result =s.trim()
    return p.matcher(s).replaceAll('') //result.replace(delimiter,'')
}

我读过原因是写入在写入之间已关闭。那是对的吗?

4

1 回答 1

0
def userDataAsCSV(){
         response.setHeader("Content-disposition","attachment; filename=User.csv")
         def lists = User.list()
         def newRecord="Id Name \n"
         lists.each{
            newRecord += "${it.id} ${it.name} \n"
         }
         render (contentType : "text/csv",text:newRecord)
}

这是从数据库数据中创建和下载 csv 文件的代码。

于 2013-10-22T10:02:55.573 回答