我有一种方法可以将 44 MB 的数据从 ResultSet 写入 CSV 文件。然而,完成大约需要 3.5 分钟。对于只有 44 MB 的数据来说,这似乎很慢。任何人都可以看到任何减慢我的代码速度的东西吗?:
public static void convertToCSV(final ResultSet rs) throws SQLException, IOException {
final BufferedWriter fw = new BufferedWriter(new FileWriter(new File("alert.csv")));
while (rs.next()) {
fw.write(rs.getString("FIELD1")+",");
fw.write(rs.getString("FIELD2")+",");
fw.write(rs.getString("FIELD3")+",");
final String clobValue = rs.getString("FIELD4");
if(clobValue==null)
fw.write("null,");
else{
fw.write("\""+clobValue+"\",");
}
final Date date = new Date(rs.getLong("FIELD5"));
final DateFormat format = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
final String dateTime[] = format.format(date).split(" ");
fw.write(dateTime[0]+",");
fw.write(dateTime[1]);
fw.write("\n");
}
fw.close();
}
最佳答案
这样的事情可能会更快
public static void convertToCSV(final ResultSet rs) throws SQLException, IOException {
final BufferedWriter fw = new BufferedWriter(new FileWriter(new File("alert.csv")));
final DateFormat format = new SimpleDateFormat("'yyyyMMdd','HH:mm:ss'");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
while (rs.next()) {
StringBuilder sb = new StringBuilder();
sb.append(rs.getString("FIELD1")).append(',')
.append(rs.getString("FIELD2")).append(',')
.append(rs.getString("FIELD3")).append(',');
final String clobValue = rs.getString("FIELD4");
if(clobValue==null)
sb.append("null,");
else{
sb.append('\"').append(clobValue).append('\"').append(',');
}
Date date = new Date(rs.getLong("FIELD5"));
sb.append(format.format(date)).append('\n');
fw.write(sb.toString());
}
fw.close();
}
DateFormat
的创建仅在循环之外完成一次。- 使用
StringBuilder
- 尽可能避免创建临时对象。
您甚至可以重用StringBuilder
,方法是将创建的内容移出循环,并在编写它后执行setLength(0)
。
关于java - BufferedWriter 性能缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33238704/