Java操作文件

tech2024-05-15  77

文章目录

1.读取excel文件2.利用StringBuffer组装数据

1.读取excel文件

public StringBuffer readExcel(Map map){ //定义一个Excel表格 XSSFWorkbook wb = null; //获取要导入的文件名路径,实例化Excel对象 if (null != map.get("xlsxName")) { String xlsxName = map.get("xlsxName"); try{ wb = new XSSFWorkbook(this.getClass().getResourceAsStream(xlsxName)); } catch (IOException e) { LOG.error("readExcel_error" + e.getMessage, e); } } //指定sheet页 Sheet sheet = wb.getSheet("sheet1"); //定义表格对象 Row row = null; //定义首行 Row firstRow = null; //定义StringBuffer对象 StringBuffer sb = new StringBuffer(); for (int i = 1; i < sheet.getLastRowNum() + 1; i++) { try{ //过滤空行 if(sheet.getRow(i) == null || sheet.getRow(i).getCell(0) == null) { continue; } firstRow = sheet.get(0); forint j = 0; j < first.getLastCellNum(); j++{ row = sheet.getRow(i); cell = row.getCell(j); if (cell != null) { sb.append(cell); } else { sb.append(""); } } //换行 sb.append(System.getProperty("line.separator")); //每2000条写入一次,然后清空stringBuffer,防止stringBuffer太大,影响性能。 if(i % 2000 == 0{ assembleTxtData(sb); sb.delete(0, sb.length()); } } catch (Exception e) { LOG.error("readExcel_error" + e.getMessage(), e); } } assembleTxtData(sb); }

2.利用StringBuffer组装数据

// file -> FileOutputStream() -> PrintWriter public void assembleTxtData(StringBuffer sb){ FileOutputStream fos = null; PrintWriter pw = null; File file = new File("D://1.txt"); try{ if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file, true);//后面的参数是判断是否在文件后面添加而不是清空重新来 pw = new PrintWriter(fos); pw.write(sb.toString().toCharArray()); pw.flush(); } catch (IOException e) { LOG.error("assembleTxtData_error" + e.getMessage(), e); } finally { if (pw != null) { pw.close(); } if (fos != null) { try { fos.close(); } catch (IOException e) { LOG.error("assembleTxtData_error" + e.getMessage(), e); } } } }
最新回复(0)