仅供参考,外加懒得整理了。。。
自动根据查询结果大小生成的CSV和ZIP方法 详看 createFilesAdd
其他方法为最初版本
另外需要注意的是,JDK1.7之前,自带的ZIP下载工作类,打包的时候 无法支持包内文件名是中文
需要更换为 org.apache.tools.zip.ZipEntry
另外GeneralDAO 为封装的mybatis的sqlsession。 有需要使用请自行替换
在反射中,方法的invoke方法,带的参数class,只支持具体类型,不支持父类类型,如map.class和hashmap.class 不能互转
不过这是JDK1.6 之上尚未做验证
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import com.paic.agy.agyConfig.biz.service.ToolsService; import com.paic.agy.agyConfig.common.dto.FileConfigDTO; import com.paic.agy.common.integration.dao.GeneralDAO; import com.paic.agy.common.util.StringUtil; import javax.servlet.http.HttpServletResponse; import com.paic.agy.common.util.Constants; import com.paic.agy.common.util.Logger; import com.paic.agy.common.util.SpringBeanUtil; public class Tools { /** * 该类中 getValue 方法 传入code_id 获取 CD表中 item_value 值 */ public static ToolsService toolsService = (ToolsService) SpringBeanUtil .getBean(ToolsService.TOOLS_SERVICE_ID); /** * 生成GeneralDAO */ public static GeneralDAO generalDAO = (GeneralDAO) SpringBeanUtil .getBean(GeneralDAO.SERVICE_ID); /** * 数字格式,保留2位小数 */ public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat( "######0.00"); /** * 数字0.00 */ public static final String ZERO = "0.00"; /** * 判断字符串是否为数字 健壮性强于正则 * * @param str * @return */ public static boolean isNumeric(String str) { @SuppressWarnings("unused") String bigStr; try { bigStr = new BigDecimal(str).toString(); } catch (Exception e) { return false;// 异常 说明包含非数字。 } return true; } /** * 首字母大写 * * @param str * @return */ public static String captureStr(String str) { char[] cs = str.toCharArray(); cs[0] -= 32; return String.valueOf(cs); } /** * * @param httpResponse * 输出流 * @param titles * CSV输出标题 * @param fields * CSV内容对应字段,应与DTO属性对应,也与 输出标题按顺序对应 * @param obj * 为Service对象 * @param intfClass * Service的Class类 * @param list * 查询结果List 需要传入带泛型的 List 如 new ArrayList<CheckAllotLevelDTO>(); * @param map * Map<String, String> countSql listSql filename * 传入参数,总条目查询方法名,结果集查询方法名,最后需要导出的文件名 * @param paramMap * Map<String, Object> 需要注意Map 内泛型类型 查询条件 * @throws Exception */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> void exportCSVALL(HttpServletResponse httpResponse, String[] titles, String[] fields, Object obj, Class intfClass, List<T> list, Map<String, String> map, Map<String, Object> paramMap) throws Exception { int total = 0; // 区分count方法查询是否带条件 try { total = (Integer) intfClass.cast(obj).getClass() .getMethod(map.get("countMethod"), paramMap.getClass()) .invoke(obj, paramMap); } catch (NoSuchMethodException e) { total = (Integer) intfClass.cast(obj).getClass() .getMethod(map.get("countMethod")).invoke(obj); } // 总数分页,每一万条为一页 int i = 1; if (total > 10000) i = total / 10000 + 1; paramMap.put("rows", 10000); OutputStream out = null; try { // 文件名 String filename = new String( map.get("fileName").getBytes("gb2312"), "ISO8859-1"); httpResponse.setContentType("application/download;charset=UTF-8"); httpResponse.setHeader("Content-disposition", "attachment;filename=\"" + filename + ".csv\""); // 获取流 out = httpResponse.getOutputStream(); // 给文件里写入标题 StringBuffer titletemp = new StringBuffer(); for (String temp : titles) { titletemp.append(temp + ","); } out.write(titletemp.toString().substring(0, titletemp.length() - 1) .getBytes()); out.write("\n".getBytes()); StringBuffer tempstr = new StringBuffer(); for (int j = 1; j <= i; j++) { paramMap.put("page", j); list = (List<T>) intfClass.cast(obj).getClass() .getMethod(map.get("listMethod"), paramMap.getClass()) .invoke(obj, paramMap); for (T x : list) { // 自动封装每一行数据 Class tempClass = x.getClass(); tempstr.delete(0, tempstr.length()); for (String ele : fields) { try { Method method = tempClass.getMethod("get" + Tools.captureStr(ele)); Object temp = method.invoke(x); tempstr.append(temp == null ? "" : temp.toString() + "\t"); } catch (Exception e) { Logger.error(tempClass, "无该属性getter方法", map.get("ele"), e); } tempstr.append(","); } out.write(tempstr.toString() .substring(0, tempstr.length() - 1).getBytes()); out.write("\n".getBytes()); } } } catch (Exception e) { Logger.error(intfClass, "下载异常", map.get("fileName"), e); throw new Exception("下载异常"); } finally { try { if (out != null) { out.close(); } } catch (IOException ioe) { Logger.error(intfClass, map.get("listMethod"), "-----下载" + map.get("fileName") + "文件:关闭输出流失败-----", ioe); } } } /** * * @param titles * CSV输出标题 * @param fields * CSV内容对应字段,应与DTO属性对应,也与 输出标题按顺序对应 * @param obj * 为Service对象 * @param intfClass * Service的Class类 * @param list * 查询结果List 需要传入带泛型的 List 如 new ArrayList<CheckAllotLevelDTO>(); * @param map * Map<String, String> countMethod listMethod fileName filePath * 传入参数:countMethod总条目查询方法名 * ,listMethod结果集查询方法名,fileName最后需要导出的文件名,filePath文件路径 * @param paramMap * Map<String, Object> 需要注意Map 内泛型类型 查询条件 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> String createFiles(String[] titles, String[] fields, Object obj, Class intfClass, List<T> list, Map<String, String> map, Map<String, Object> paramMap) throws Exception { if (paramMap == null) paramMap = new HashMap<String, Object>(); // 数据库总条目 int total = 0; // 分页总次数 int i = 1; try { total = (Integer) intfClass.cast(obj).getClass() .getMethod(map.get("countMethod"), paramMap.getClass()) .invoke(obj, paramMap); } catch (NoSuchMethodException e) { total = (Integer) intfClass.cast(obj).getClass() .getMethod(map.get("countMethod")).invoke(obj); } String nasPath = SpringBeanUtil.getProperties( Constants.BEAN_SYSTEMPROPERTIES).getProperty( Constants.AGY_NAS_KEY); // 验证NAS路径是否为空 if (StringUtil.isEmptyStr(nasPath)) { throw new Exception("NAS路径为空!"); } // 获取全路径 String fileSuffix = new SimpleDateFormat("yyyyMMdd").format(new Date()); String reportDir = nasPath + File.separator + map.get("filePath") + File.separator + fileSuffix; // 生成目录 File uploadFileDir = new File(reportDir); if (!uploadFileDir.exists()) uploadFileDir.mkdirs(); Integer sectionNumber = 500000; String sectionStr = toolsService.getValue("zipSectionNumber"); if (Tools.isNumeric(sectionStr)) sectionNumber = Integer.parseInt(sectionStr); String pageSizeStr = toolsService.getValue("pageSize"); Integer pageSize = 10000; if (Tools.isNumeric(pageSizeStr)) pageSize = Integer.parseInt(pageSizeStr); if (total < sectionNumber) { if (total > pageSize) i = total / pageSize + 1; paramMap.put("rows", pageSize); PrintStream ps = null; try { String filename = map.get("fileName") + ".csv"; String filestr = reportDir + File.separator + filename; File file = new File(filestr); file.createNewFile(); ps = new PrintStream(new FileOutputStream(file)); StringBuffer titletemp = new StringBuffer(); for (String temp : titles) { titletemp.append(temp + ","); } ps.write(titletemp.toString() .substring(0, titletemp.length() - 1).getBytes()); ps.write("\n".getBytes()); StringBuffer tempstr = new StringBuffer(); for (int j = 1; j <= i; j++) { paramMap.put("page", j); list = (List<T>) intfClass .cast(obj) .getClass() .getMethod(map.get("listMethod"), paramMap.getClass()).invoke(obj, paramMap); for (T x : list) { Class tempClass = x.getClass(); tempstr.delete(0, tempstr.length()); for (String ele : fields) { Method method = tempClass.getMethod("get" + Tools.captureStr(ele)); Object temp = method.invoke(x); tempstr.append(temp == null ? "" : temp.toString() + "\t"); tempstr.append(","); } ps.write(tempstr.toString() .substring(0, tempstr.length() - 1).getBytes()); ps.write("\n".getBytes()); ps.flush(); } } return reportDir + File.separator + filename; } catch (Exception e) { Logger.error(intfClass, "生成文件异常", map.get("fileName"), e); throw new Exception("生成文件异常"); } finally { try { if (ps != null) { ps.close(); } } catch (Exception e) { Logger.error(intfClass, map.get("listMethod"), "-----关闭" + map.get("fileName") + "输出流失败-----", e); } } } else { // 大于50万 自动生成zip文件 // 文件分段次数 Integer times = total / sectionNumber + 1; // 总页码数量 i = total / pageSize + 1; // 页码分段数量 Integer pages = i / times; paramMap.put("rows", pageSize); PrintStream ps = null; // 文件List List<File> fileList = new ArrayList<File>(); FileOutputStream fos = null; ZipOutputStream zos = null; try { for (int j = 1; j <= times; j++) { String filename = map.get("fileName") + j + ".csv"; File file = new File(reportDir + File.separator + filename); if (file == null || !file.exists()) file.createNewFile(); fileList.add(file); ps = new PrintStream(new FileOutputStream(file)); StringBuffer titletemp = new StringBuffer(); for (String temp : titles) { titletemp.append(temp + ","); } ps.write(titletemp.toString() .substring(0, titletemp.length() - 1).getBytes()); ps.write("\n".getBytes()); StringBuffer tempstr = new StringBuffer(); for (int k = 1; k <= pages; k++) { int pageNum = k + (j - 1) * pages; if (pageNum > i) break; // 写入内容 paramMap.put("page", j); list = (List<T>) intfClass .cast(obj) .getClass() .getMethod(map.get("listMethod"), paramMap.getClass()) .invoke(obj, paramMap); for (T x : list) { Class tempClass = x.getClass(); tempstr.delete(0, tempstr.length()); for (String ele : fields) { Method method = tempClass.getMethod("get" + Tools.captureStr(ele)); Object temp = method.invoke(x); tempstr.append(temp == null ? "" : temp .toString() + "\t"); tempstr.append(","); } ps.write(tempstr.toString() .substring(0, tempstr.length() - 1) .getBytes()); ps.write("\n".getBytes()); ps.flush(); } } } String filename = map.get("fileName") + ".zip"; File zipFile = new File(reportDir + File.separator + filename); // 获取ZIP文件流 fos = new FileOutputStream(zipFile); zos = new ZipOutputStream(new BufferedOutputStream(fos)); // 生成zip Tools.zipFile(fileList, zos); // 删除已经打包的文件 for (File file : fileList) { file.deleteOnExit(); } return reportDir + File.separator + filename; } catch (Exception e) { Logger.error(intfClass, "生成ZIP文件异常", map.get("fileName"), e); throw new Exception("生成ZIP文件异常"); } finally { try { if (ps != null) { ps.close(); } if (zos != null) { zos.close(); } if (fos != null) { fos.close(); } } catch (Exception e) { Logger.error(intfClass, map.get("listMethod"), "-----关闭" + map.get("fileName") + "输出流失败-----", e); throw new Exception( "-----关闭" + map.get("fileName") + "输出流失败-----"); } } } } /** * * @param titles * CSV输出标题 * @param fields * CSV内容对应字段,应与DTO属性对应,也与 输出标题按顺序对应 * @param obj * 为Service对象 * @param intfClass * Service的Class类 * @param list * 查询结果List 需要传入带泛型的 List 如 new ArrayList<CheckAllotLevelDTO>(); * @param map * Map<String, String> countMethod listMethod fileName filePath * 传入参数:countMethod总条目查询方法名 * ,listMethod结果集查询方法名,fileName最后需要导出的文件名,filePath文件路径 * @param paramMap * Map<String, Object> 需要注意Map 内泛型类型 查询条件 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> String createFiles(String[] titles, String[] fields, List<T> list, FileConfigDTO dto, Map<String, Object> paramMap) throws Exception { if (paramMap == null) paramMap = new HashMap<String, Object>(); // 数据库总条目 int total = 0; // 分页总次数 int i = 1; total = (Integer) generalDAO.queryForObject(dto.getCountSQLId(), paramMap); String nasPath = SpringBeanUtil.getProperties( Constants.BEAN_SYSTEMPROPERTIES).getProperty( Constants.AGY_NAS_KEY); // 验证NAS路径是否为空 if (StringUtil.isEmptyStr(nasPath)) { throw new Exception("NAS路径为空!"); } // 获取全路径 String fileSuffix = new SimpleDateFormat("yyyyMMdd").format(new Date()); String reportDir = nasPath + File.separator + dto.getFilePath() + File.separator + fileSuffix; // 生成目录 File uploadFileDir = new File(reportDir); if (!uploadFileDir.exists()) uploadFileDir.mkdirs(); Integer sectionNumber = 500000; String sectionStr = toolsService.getValue("zipSectionNumber"); if (Tools.isNumeric(sectionStr)) sectionNumber = Integer.parseInt(sectionStr); String pageSizeStr = toolsService.getValue("pageSize"); Integer pageSize = 10000; if (Tools.isNumeric(pageSizeStr)) pageSize = Integer.parseInt(pageSizeStr); if (total < sectionNumber) { if (total > pageSize) i = total / pageSize + 1; paramMap.put("rows", pageSize); PrintStream ps = null; try { String filename = dto.getFileName() + ".csv"; String filestr = reportDir + File.separator + filename; File file = new File(filestr); file.createNewFile(); ps = new PrintStream(new FileOutputStream(file)); StringBuffer titletemp = new StringBuffer(); for (String temp : titles) { titletemp.append(temp + ","); } ps.write(titletemp.toString() .substring(0, titletemp.length() - 1).getBytes()); ps.write("\n".getBytes()); StringBuffer tempstr = new StringBuffer(); for (int j = 1; j <= i; j++) { paramMap.put("page", j); list = (List<T>) generalDAO.queryForList( dto.getListSQLId(), paramMap); for (T x : list) { Class tempClass = x.getClass(); tempstr.delete(0, tempstr.length()); for (String ele : fields) { Method method = tempClass.getMethod("get" + Tools.captureStr(ele)); Object temp = method.invoke(x); tempstr.append(temp == null ? "" : temp.toString() + "\t"); tempstr.append(","); } ps.write(tempstr.toString() .substring(0, tempstr.length() - 1).getBytes()); ps.write("\n".getBytes()); ps.flush(); } } return reportDir + File.separator + filename; } catch (Exception e) { Logger.error(Tools.class, "生成文件异常", dto.getFileName(), e); throw new Exception("生成文件异常"); } finally { try { if (ps != null) { ps.close(); } } catch (Exception e) { Logger.error(Tools.class,"关闭流异常", "createFiles", e); } } } else { // 大于50万 自动生成zip文件 // 文件分段次数 Integer times = total / sectionNumber + 1; // 总页码数量 i = total / pageSize + 1; // 页码分段数量 Integer pages = i / times; paramMap.put("rows", pageSize); PrintStream ps = null; // 文件List List<File> fileList = new ArrayList<File>(); FileOutputStream fos = null; ZipOutputStream zos = null; try { for (int j = 1; j <= times; j++) { String filename = dto.getFileName() + j + ".csv"; File file = new File(reportDir + File.separator + filename); if (file == null || !file.exists()) file.createNewFile(); fileList.add(file); ps = new PrintStream(new FileOutputStream(file)); StringBuffer titletemp = new StringBuffer(); for (String temp : titles) { titletemp.append(temp + ","); } ps.write(titletemp.toString() .substring(0, titletemp.length() - 1).getBytes()); ps.write("\n".getBytes()); StringBuffer tempstr = new StringBuffer(); for (int k = 1; k <= pages; k++) { int pageNum = k + (j - 1) * pages; if (pageNum > i) break; // 写入内容 paramMap.put("page", j); list = (List<T>) generalDAO.queryForList( dto.getListSQLId(), paramMap); for (T x : list) { Class tempClass = x.getClass(); tempstr.delete(0, tempstr.length()); for (String ele : fields) { Method method = tempClass.getMethod("get" + Tools.captureStr(ele)); Object temp = method.invoke(x); tempstr.append(temp == null ? "" : temp .toString() + "\t"); tempstr.append(","); } ps.write(tempstr.toString() .substring(0, tempstr.length() - 1) .getBytes()); ps.write("\n".getBytes()); ps.flush(); } } } String filename = dto.getFileName() + ".zip"; File zipFile = new File(reportDir + File.separator + filename); // 获取ZIP文件流 fos = new FileOutputStream(zipFile); zos = new ZipOutputStream(new BufferedOutputStream(fos)); // 生成zip Tools.zipFile(fileList, zos); // 删除已经打包的文件 for (File file : fileList) { file.deleteOnExit(); } return reportDir + File.separator + filename; } catch (Exception e) { Logger.error(Tools.class, "生成ZIP文件异常","createFile", e); throw e; } finally { try { if (ps != null) { ps.close(); } if (zos != null) { zos.close(); } if (fos != null) { fos.close(); } } catch (Exception e) { Logger.error(Tools.class, "-----关闭输出流失败-----", "createFile", e); throw e; } } } } /** * @param titles * CSV输出标题 * @param fields * CSV内容对应字段,应与DTO属性对应,也与 输出标题按顺序对应 * @param list * 查询结果List 需要传入带泛型的 List 如 new ArrayList<CheckAllotLevelDTO>(); * @param dto * 参考DTO注释 * @param paramMap * Map<String, Object> 需要注意Map 内泛型类型 查询条件 * @return * @throws Exception */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> String createFilesAdd(String[] titles, String[] fields, List<T> list, FileConfigDTO dto, Map<String, Object> paramMap) throws Exception { if (paramMap == null) paramMap = new HashMap<String, Object>(); // 数据库总条目 int total = 0; // 文件内部条目数量 int CSVCount = 0; // 文件夹内总文件数 int filenumber = 0; // 分页总次数 int i = 1; // 是否需要写入标题 boolean isWriteTitle = false; total = (Integer) generalDAO.queryForObject(dto.getCountSQLId(), paramMap); // 获取nas路径 String nasPath = SpringBeanUtil.getProperties( Constants.BEAN_SYSTEMPROPERTIES).getProperty( Constants.AGY_NAS_KEY); // 验证NAS路径是否为空 if (StringUtil.isEmptyStr(nasPath)) { throw new Exception("NAS路径为空!"); } // 获取全路径 String fileSuffix = new SimpleDateFormat("yyyyMMdd").format(new Date()); String reportDir = nasPath + File.separator + dto.getFilePath() + File.separator + fileSuffix; //用于保存数据库文件路径 String fileurl = nasPath +"-path-"+dto.getFilePath() +"-path-"+ fileSuffix; // 生成目录 File uploadFileDir = new File(reportDir); if (!uploadFileDir.exists()) { uploadFileDir.mkdirs(); } else { filenumber = readFileNumbers(reportDir); } Integer sectionNumber = 500000; String sectionStr = toolsService.getValue("zipSectionNumber"); if (Tools.isNumeric(sectionStr)) sectionNumber = Integer.parseInt(sectionStr); String pageSizeStr = toolsService.getValue("pageSize"); Integer pageSize = 10000; if (Tools.isNumeric(pageSizeStr)) pageSize = Integer.parseInt(pageSizeStr); // 测试数据 // sectionNumber = 5; // pageSize = 3; String fileName = dto.getFileName() + ".csv"; String filestr = reportDir + File.separator + fileName; File lastfile = null; if (filenumber == 1) { lastfile = new File(filestr); if (lastfile != null && lastfile.exists()) { CSVCount = Tools.getCSVFileCount(lastfile); } } else if (filenumber == 0) { lastfile = new File(filestr); lastfile.createNewFile(); isWriteTitle = true; // 已经创建了文件 filenumber+1 filenumber++; } else { // 多文件的时候获取最新那个CSV文件 String moreName = dto.getFileName() + (filenumber - 2) + ".csv"; String morePath = reportDir + File.separator + moreName; lastfile = new File(morePath); if (lastfile != null && lastfile.exists()) { CSVCount = Tools.getCSVFileCount(lastfile); } } // 获取剩余空间数量 int overplus = sectionNumber - CSVCount; // 小于1则为0 overplus = overplus < 1 ? 0 : overplus; if ((total + CSVCount) < sectionNumber && filenumber <= 1) { if (total > pageSize) i = total / pageSize + 1; paramMap.put("rows", pageSize); BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(lastfile, true)); // ps = new PrintStream(new FileOutputStream(onefile)); StringBuffer titletemp = new StringBuffer(); if (isWriteTitle) { for (String temp : titles) { titletemp.append(temp + ","); } bw.write(titletemp.toString().substring(0, titletemp.length() - 1)); bw.newLine(); isWriteTitle = false; } StringBuffer tempstr = new StringBuffer(); for (int j = 1; j <= i; j++) { paramMap.put("page", j); list = (List<T>) generalDAO.queryForList( dto.getListSQLId(), paramMap); for (T x : list) { Class tempClass = x.getClass(); tempstr.delete(0, tempstr.length()); for (String ele : fields) { Method method = tempClass.getMethod("get" + Tools.captureStr(ele)); Object temp = method.invoke(x); tempstr.append(temp == null ? "" : temp.toString() + "\t"); tempstr.append(","); } Tools.addToCSVFile( tempstr.toString().substring(0, tempstr.length() - 1), bw); } } return fileurl + "-path-"+ fileName; } catch (Exception e) { Logger.error(Tools.class, "生成文件异常", dto.getFileName(), e); e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } } catch (Exception e) { Logger.error(Tools.class, dto.getListSQLId(), "-----关闭" + dto.getFileName() + "输出流失败-----", e); } } } else { // 大于50万 自动生成zip文件 // 计算需要创建的新文件夹数量,为 总数减去 当前文件剩余空间 除以分段数 Integer filesNum = (total - overplus) % sectionNumber == 0 ? ((total - overplus) / sectionNumber) : ((total - overplus) / sectionNumber + 1); // 总页码数量 i = total / pageSize + 1; paramMap.put("rows", pageSize); // 文件List List<File> fileList = new ArrayList<File>(); FileOutputStream fos = null; ZipOutputStream zos = null; if (overplus > 0) { fileList.add(lastfile); } else { isWriteTitle = true; } if (filenumber == 1) filenumber = 1; else filenumber--; int nowFile = 0; for (int j = 0; j < filesNum; j++) { String filename = dto.getFileName() + (filenumber++) + ".csv"; File file = new File(reportDir + File.separator + filename); if (file == null || !file.exists()) file.createNewFile(); fileList.add(file); } BufferedWriter bw = null; try { File file = null; file = fileList.get(nowFile); bw = new BufferedWriter(new FileWriter(file, true)); for (int j = 1; j <= i; j++) { // ps = new PrintStream(new FileOutputStream(onefile)); StringBuffer tempstr = new StringBuffer(); // 写入内容 paramMap.put("page", j); list = (List<T>) generalDAO.queryForList( dto.getListSQLId(), paramMap); for (T x : list) { if (overplus < 1) { nowFile++; overplus = sectionNumber; file = fileList.get(nowFile); isWriteTitle = true; // 清流缓存和关闭流 很重要 if (bw != null) { bw.flush(); bw.close(); } bw = new BufferedWriter(new FileWriter(file, true)); } if (isWriteTitle) { StringBuffer titletemp = new StringBuffer(); for (String temp : titles) { titletemp.append(temp + ","); } bw.write(titletemp.toString().substring(0, titletemp.length() - 1)); bw.newLine(); isWriteTitle = false; } Class tempClass = x.getClass(); tempstr.delete(0, tempstr.length()); for (String ele : fields) { Method method = tempClass.getMethod("get" + Tools.captureStr(ele)); Object temp = method.invoke(x); tempstr.append(temp == null ? "" : temp.toString() + "\t"); tempstr.append(","); } Tools.addToCSVFile( tempstr.toString().substring(0, tempstr.length() - 1), bw); // 剩余空间减一 overplus--; } } // 清流缓存和关闭流 很重要 if (bw != null) { bw.flush(); bw.close(); } fileList.clear(); for (int j = 0; j < filenumber; j++) { String filename = null; if (j == 0) { filename = dto.getFileName() + ".csv"; } else { filename = dto.getFileName() + j + ".csv"; } File otherFile = new File(reportDir + File.separator + filename); if (otherFile != null || otherFile.exists()) fileList.add(otherFile); } String filename = dto.getFileName() + ".zip"; File zipFile = new File(reportDir + File.separator + filename); // 获取ZIP文件流 fos = new FileOutputStream(zipFile); zos = new ZipOutputStream(new BufferedOutputStream(fos)); // 生成zip Tools.zipFile(fileList, zos); return fileurl + "-path-"+ filename; } catch (Exception e) { Logger.error(Tools.class, "生成ZIP文件异常", dto.getFileName(), e); e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } if (zos != null) { zos.close(); } if (fos != null) { fos.close(); } } catch (Exception e) { Logger.error(Tools.class, dto.getListSQLId(), "-----关闭" + dto.getFileName() + "输出流失败-----", e); } } } throw new Exception("文件创建失败!"); } /** * 将其他文件打包成zip文件 * * @param files * 需要打包的文件list * @param outputStream * zip文件流 */ public static void zipFile(List<File> files, ZipOutputStream outputStream) { int size = files.size(); for (int i = 0; i < size; i++) { File file = (File) files.get(i); // 将要打包的文件写入zip文件中 Tools.zipFile(file, outputStream); } } /** * zip 写入方法 * * @param inputFile * @param ouputStream */ public static void zipFile(File inputFile, ZipOutputStream ouputStream) { try { if (inputFile.exists()) { // 判断是否文件 if (inputFile.isFile()) { FileInputStream IN = new FileInputStream(inputFile); BufferedInputStream bins = new BufferedInputStream(IN, 512); // org.apache.tools.zip.ZipEntry 需要该类型才能保证压缩文件夹中文件名为中文 ZipEntry entry = new ZipEntry(inputFile.getName()); ouputStream.putNextEntry(entry); // 向压缩文件中输出数据 int nNumber; byte[] buffer = new byte[512]; while ((nNumber = bins.read(buffer)) != -1) { ouputStream.write(buffer, 0, nNumber); } // 关闭创建的流对象 bins.close(); IN.close(); } else { try { File[] files = inputFile.listFiles(); for (int i = 0; i < files.length; i++) { zipFile(files[i], ouputStream); } } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } finally { } } /** * 传输文件路径去下载 * * @param filePath * @param response * @param fileNewName */ public static void downLoadFile(String filePath, HttpServletResponse response, String fileNewName) { File f = new File(filePath); OutputStream out = null; BufferedInputStream br = null; try { out = response.getOutputStream(); if (!f.exists()) { response.setCharacterEncoding("ISO8859-1"); out.write("file not found!".getBytes()); out.flush(); return; } br = new BufferedInputStream(new FileInputStream(f)); byte[] buf = new byte[1024]; int len = 0; fileNewName = new String(fileNewName.getBytes("gb2312"), "ISO8859-1"); response.reset(); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + fileNewName + filePath.substring(filePath.length() - 4)); while ((len = br.read(buf)) > 0) response.getOutputStream().write(buf, 0, len); response.getOutputStream().flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (br != null) { br.close(); } } catch (Exception e) { e.printStackTrace(); } } } /** * 读取CSV有多少行 * * @param file * @return */ @SuppressWarnings("unused") public static int getCSVFileCount(File file) { int count = 0; BufferedReader reader = null; if (file == null || !file.exists()) return 0; try { reader = new BufferedReader(new FileReader(file));// 换成你的文件名 reader.readLine();// 第一行信息,为标题信息,不用,如果需要,注释掉 String line = null; while ((line = reader.readLine()) != null) { count++; } } catch (Exception e) { Logger.error(Tools.class, "getCSVFileCount", "读取CSV文件错误", e); } finally { try { reader.close(); } catch (IOException e) { Logger.error(Tools.class, "getCSVFileCount", "关闭流错误", e); } } return count; } /** * 文件追加内容方法 * * @param content * @param bw */ public static void addToCSVFile(String content, BufferedWriter bw) { try { // 流的关闭操作放入外面防止反复创建 增加开销 if (bw == null) return; // bw = new BufferedWriter(new FileWriter(file, true)); bw.write(content); bw.newLine(); } catch (Exception e) { Logger.error(Tools.class, "addToCSVFile", "写入CSV文件错误", e); } } /** * 读取有文件夹内有多少文件 * * @param filePath * @return */ public static int readFileNumbers(String filePath) { // 文件数量 int fileCount = 0; // 文件夹数量 File d = new File(filePath); if (d == null || !d.exists()) return 0; if (!d.isDirectory()) d = d.getParentFile(); File list[] = d.listFiles(); for (int i = 0; i < list.length; i++) { if (list[i].isFile()) { fileCount++; } } return fileCount; } }