public class CsvUtil { // 编码类型 public static final Charset CHARSET = Charset.forName( "GBK" ); // 分隔符 public static final char DELIMITER = ',' ; // 文件后缀 public static final String SUFFIX = ".csv" ; public static void writeCsv(OutputStream out, String[] header, ResultSet rs) throws IOException, SQLException { CsvWriter writer = null ; try { writer = new CsvWriter(out, CsvUtil.DELIMITER, CsvUtil.CHARSET); writeCsv(writer, header, rs); } finally { if (writer != null ) writer.close(); } } public static void writeCsv(CsvWriter writer, String[] header, ResultSet rs) throws IOException, SQLException { if (header != null ) writer.writeRecord(header); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()) { for ( int i = 1 ; i <= columnCount; i++) writer.write(rs.getString(i)); writer.endRecord(); } } public static void writeCsv(File file, String[] header, ResultSet rs) throws IOException, SQLException { BufferedOutputStream out = null ; FileOutputStream fileOutputStream = null ; try { fileOutputStream = new FileOutputStream(file); out = new BufferedOutputStream(fileOutputStream); writeCsv(out, header, rs); } finally { if (out != null ) { out.flush(); out.close(); } if (fileOutputStream != null ) { fileOutputStream.close(); } } } public static void writeCsv(String csvFilePath, String[] header, ResultSet rs) throws IOException, SQLException { writeCsv( new File(csvFilePath), header, rs); } public static void writeCsv(String zipFilePath, String csvName, String[] header, ResultSet rs) throws IOException, SQLException { FileOutputStream fos = null ; BufferedOutputStream bos = null ; ZipOutputStream zos = null ; try { fos = new FileOutputStream(zipFilePath); bos = new BufferedOutputStream(fos); zos = new ZipOutputStream(bos); zos.putNextEntry( new ZipEntry(csvName)); writeCsv(zos, header, rs); } finally { StreamUtil.flush(zos); StreamUtil.close(zos); //StreamUtil.flush(bos); StreamUtil.close(bos); //StreamUtil.flush(fos); StreamUtil.close(fos); } } } |