I am using this code to write more than 170,000 rows to an Excel document. All in all, the file generation process takes about 3 minutes total. (I've already shaved off about ten minutes by shaving off overhead in the form of Apache POI and an unnecessary ArrayList) I'd like to shave off some more time, but I'm currently out of ideas.
public File generateDelimitedFile(String sql, String outputFilename, String delimiter, String bodyStringDelim) throws SQLException, IOException{
File output = new File(outputFilename);
try (
Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)
) {
resultSet.setFetchSize(excelFetchSize);
ResultSetMetaData meta = resultSet.getMetaData();
int columnCount = meta.getColumnCount();
StringBuilder headerBuilder = new StringBuilder();
for (int i = 1; i < columnCount + 1; i++ ) {
String name = meta.getColumnName(i);
headerBuilder.append(name);
if (i != columnCount) {
headerBuilder.append(delimiter);
}
}
FileUtils.writeStringToFile(output, headerBuilder.toString(), true);
while(resultSet.next()) {
StringBuilder lineBuilder = new StringBuilder();
for (int column = 1; column <= columnCount; column++) {
String value = resultSet.getString(column);
if (value != null) {
if(bodyStringDelim != null){
lineBuilder.append(bodyStringDelim);
}
lineBuilder.append(value);
if(bodyStringDelim != null){
lineBuilder.append(bodyStringDelim);
}
}
if (column != columnCount) {
lineBuilder.append(delimiter);
}
}
FileUtils.writeStringToFile(output, lineBuilder.toString(), true);
}
logger.info("Writing data to file");
} catch (SQLException ex) {
logger.error("Error generating file from SQL", ex);
throw ex;
} catch (IOException ex) {
logger.error("Error writing file", ex);
throw ex;
}
return output;
}
FileUtils.writeStringToFile()
? From the looks of it, that will need to open the file again and again. Without profiling though, it's just a guess whether that is your current bottleneck. \$\endgroup\$ – bowmore Jul 17 '14 at 17:51FileUtils.writeStringToFile()
. \$\endgroup\$ – BarFooBar Jul 17 '14 at 18:09