CSV File Generation is too slow : <p>Hi i am using the following code to generate the CSV file using the java servlet but it is taking 40mins to generate a CSV file with no. of rows 3000. is there any other optimized code which can speed up my CSV generation to 1 or 2 mins.
My code is here  :</p>

<pre><code>protected void getCSVReportGererated(HttpServletRequest req, HttpServletResponse res) throws IOException{   
        ResultSet rs = null;
        String reportSQL = getReportSQL();
        PreparedStatement ps = null;
        Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/testDb","username", "password");
        try{
            ps = conn.prepareStatement(reportSQL);
            ps.execute();
            rs = ps.getResultSet();
            res.setContentType("text/csv");
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy-HHMM");
            Date dt = new Date();
            String reportName = "my_report"+sdf.format(dt)+".csv";
            res.setHeader("Content-disposition", "attachment; " + "filename=" + reportName);
            ArrayList&lt;String&gt; rows = new ArrayList&lt;String&gt;();
            rows.add("col1,col2,col3,col4,col5,col6,col7,col8,col9,col10");
            rows.add("\n");
            String row = null;
            while(rs.next()){
                row = String.format("%04d", Integer.parseInt(rs.getString(1)))+","+String.format("%05d", Integer.parseInt(rs.getString(2)))+","+rs.getString(3)+","+rs.getString(4)+","+rs.getString(5)+","+rs.getString(6)+","+rs.getString(7)+","+rs.getString(8)+","+rs.getString(9)+","+rs.getString(10);
                rows.add(row);
                rows.add("\n");
            }
                Iterator&lt;String&gt; iter = rows.iterator();
                while (iter.hasNext()){
                    String outputString = (String) iter.next();
                    res.getOutputStream().print(outputString);
                }
                res.getOutputStream().flush();
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            try {
                if (ps != null)
                    ps.close();
                if (conn != null)
                    conn.close();
                if(rs != null)
                    rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }       
        }
}
</code></pre>
