1. 读取txt文件:
使用ClassPathResource的原因在https://blog.csdn.net/nnnora/article/details/80734326中阐述过,因为是springboot内置web容器所以不能使用FileInputStream的方式获取文件流。
//读取txt文件 ClassPathResource classPathResource = new ClassPathResource("test.txt"); InputStreamReader inputStreamReader = new InputStreamReader(classPathResource.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuffer buffer = new StringBuffer(); String line = null; while( (line = bufferedReader.readLine()) != null ){ buffer.append(line); } bufferedReader.close(); String buffer = buffer.toString();
2. 写入txt文件:
//写入txt BufferedWriter bufw = new BufferedWriter(new FileWriter("D:\\test\\result.txt")); for(Map.Entry<String, Integer> me : list){ bufw.write(me+""); bufw.newLine(); } bufw.close();
3. 读取word文档
1. 首先需要引入以下jar包:
分别是操作doc和docx格式需要的jar包,关于引入jar包的语句格式可以去http://jareye.com/查找,可以导出maven或者gradle等工具下的compile语句。
2. 读取word文档:
try { //读取word文件 String path = "Shocking level of sexual harassment at music festivals.docx"; String buffer = ""; if (path.endsWith(".doc")) { ClassPathResource classPathResource = new ClassPathResource(path); WordExtractor wordExtractor = new WordExtractor(classPathResource.getInputStream()); buffer = wordExtractor.getText(); } else if (path.endsWith("docx")) { ClassPathResource classPathResource = new ClassPathResource(path); XWPFDocument xdoc = new XWPFDocument(classPathResource.getInputStream()); POIXMLTextExtractor extractor = new XWPFWordExtractor(xdoc); buffer = extractor.getText(); } else { System.out.println("此文件不是word文件!"); } }catch (Exception e){ logger.error("@@ReadFileError", e); }
4. 写入excel文档
//写入excel //第一步,创建一个workbook对应一个excel文件 HSSFWorkbook workbook = new HSSFWorkbook(); //第二步,在workbook中创建一个sheet对应excel中的sheet HSSFSheet sheet = workbook.createSheet("词频文件"); //第三步,在sheet表中添加表头第0行,老版本的poi对sheet的行列有限制 HSSFRow row = sheet.createRow(0); //第四步,创建单元格,设置表头 HSSFCell cell = row.createCell(0); cell.setCellValue("单词"); cell = row.createCell(1); cell.setCellValue("频次"); //第五步,写入实体数据 int i = 0; for(Map.Entry<String, Integer> entity : list){ HSSFRow row1 = sheet.createRow(i + 1); row1.createCell(0).setCellValue(entity.getKey()); row1.createCell(1).setCellValue(entity.getValue()); i++; } //将文件保存到指定的位置 try { fos = new FileOutputStream("wordsResult.xls"); workbook.write(fos); logger.info("写入成功"); fos.close(); } catch (IOException e) { logger.error("@@WriteFileError", e); }