写入 CSV 文件:IOException:流已关闭

Posted

技术标签:

【中文标题】写入 CSV 文件:IOException:流已关闭【英文标题】:Writing CSV file: IOException: Stream closed 【发布时间】:2013-10-22 07:48:42 【问题描述】:

我的 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,'')

我读到原因是写入已在两次写入之间关闭。对吗?

【问题讨论】:

你发布的代码太少了。 【参考方案1】:
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 文件的代码。

【讨论】:

我认为你用纯 java.in grails 编写了复杂的代码,使用 groovy.see csv 插件或导出插件是最简单的方法。

以上是关于写入 CSV 文件:IOException:流已关闭的主要内容,如果未能解决你的问题,请参考以下文章

java.io.IOException:流已重置:多个设备上的 REFUSED_STREAM

Java读取CSV数据并写入txt文件

关于Java中向文件写入数据的问题

java 读取CSV数据并写入txt文本

3 分钟无操作后,Firestore“流已删除”错误

java要怎么修改csv中指定行列位置的值