我的 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,'')
}
我读过原因是写入在写入之间已关闭。那是对的吗?