FileUtil
package com.example.utils.file;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class FileUtil {
private ArrayList<String> data = new ArrayList<>();
public String fileRead(String path) throws Exception {
File file = new File(path);
FileReader reader = new FileReader(file);
BufferedReader bReader = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String s = "";
while ((s =bReader.readLine()) != null) {
sb.append(s + "\n");
}
bReader.close();
String str = sb.toString();
return str;
}
public String getTemplateContent(String path) throws Exception{
File file = new File(path);
if(!file.exists()){
return null;
}
FileInputStream inputStream = new FileInputStream(file);
int length = inputStream.available();
byte bytes[] = new byte[length];
inputStream.read(bytes);
inputStream.close();
String str =new String(bytes, StandardCharsets.UTF_8);
return str ;
}
public void TextToFile(final String strFilename, final String strBuffer) {
try {
File fileText = new File(strFilename);
FileWriter fileWriter = new FileWriter(fileText);
fileWriter.write(strBuffer);
fileWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<String> getFiles(String path) {
File file = new File(path);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
getFiles(files[i].getPath());
} else {
data.add(files[i].getPath());
}
}
} else {
}
return data;
}
public boolean createFile(String destFileName) {
File file = new File(destFileName);
if(file.exists()) {
log.info("创建文件" + destFileName + "失败,目标文件已存在!");
return false;
}
if (destFileName.endsWith(File.separator)) {
log.error("创建文件" + destFileName + "失败,目标文件不能为目录!");
return false;
}
if(!file.getParentFile().exists()) {
log.info("目标文件所在目录不存在,准备创建它!");
if(!file.getParentFile().mkdirs()) {
log.error("创建目标文件所在目录失败!");
return false;
}
}
try {
if (file.createNewFile()) {
log.info("创建文件" + destFileName + "成功!");
return true;
} else {
log.error("创建文件" + destFileName + "失败!");
return false;
}
} catch (IOException e) {
e.printStackTrace();
log.error("创建文件" + destFileName + "失败!" + e.getMessage());
return false;
}
}
public boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
log.error("创建目录" + destDirName + "失败,目标目录已经存在");
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
if (dir.mkdirs()) {
log.info("创建目录" + destDirName + "成功!");
return true;
} else {
log.error("创建目录" + destDirName + "失败!");
return false;
}
}
public boolean isFileExist(String fileName) {
return new File(fileName).isFile();
}
public boolean deleteFile(String filePath)
{
File f=new File(filePath);
if(f.isFile()&&f.exists())
{
return f.delete();
}
return false;
}
public boolean delAll(String filePath) {
boolean flag = true;
if(filePath != null) {
File file = new File(filePath);
if(file.exists()) {
File[] filePaths = file.listFiles();
for(File f : filePaths) {
if(f.isFile()) {
f.delete();
}
if(f.isDirectory()){
String fpath = f.getPath();
delAll(fpath);
f.delete();
}
}
}
}else {
flag = false;
}
return flag;
}
public static void main(String[] args) {
FileUtil fileUtil = new FileUtil();
if (fileUtil.isFileExist("D:\\AAA\\BB\\test.txt")) {
System.out.println("存在");
}
if (fileUtil.deleteFile("D:\\AAA\\BB\\test.txt")) {
System.out.println("删除成功");
}
}
}
ExcelUtil
package com.example.utils.excel;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.util.*;
public class ExcelUtil {
public ArrayList<HashMap<String, Object>> importFromExcel(InputStream inputStream) throws IOException {
ArrayList<HashMap<String, Object>> data = new ArrayList<>();
Workbook workBook;
try {
workBook = WorkbookFactory.create(inputStream);
} catch (Exception e) {
return null;
}
Sheet sheet = workBook.getSheetAt(0);
Row row;
for (int rowIndex = 1; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) {
row = sheet.getRow(rowIndex);
if (row == null) {
continue;
}
HashMap<String, Object> rowMap = new HashMap<>();
for(int cellnum = 0;cellnum<row.getLastCellNum(); cellnum++){
Cell cell = row.getCell(cellnum);
if (cell != null) {
rowMap.put(String.valueOf(cellnum), getCellValue(cell));
}
if (cell == null) {
rowMap.put(String.valueOf(cellnum),null);
}
}
data.add(rowMap);
}
return data;
}
public <T> void exportToExcel(Map<String,String> headers, List<T> dataset, OutputStream out) {
String pattern = "yyyy-MM-dd";
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
XSSFRow row = sheet.createRow(0);
Iterator iter = headers.entrySet().iterator();
int c= 0;
ArrayList<String> keys = new ArrayList<>();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
XSSFCell cell = row.createCell(c);
keys.add(key.toString());
cell.setCellValue(val.toString());
c++;
}
for (int i = 0; i < dataset.size(); i++) {
XSSFRow rowTemp = sheet.createRow(i+1);
Map temp = (Map) dataset.get(i);
for (int j = 0; j < keys.size(); j++) {
String value=null;
if (temp.get(keys.get(j)) != null) {
value=temp.get(keys.get(j)).toString();
}
Cell cell = rowTemp.createCell(j);
cell.setCellValue(value);
}
}
for (int i = 0; i < headers.size(); i++) {
sheet.autoSizeColumn(i);
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
private static Object getCellValue(Cell cell) {
if (cell == null
|| (cell.getCellTypeEnum() == CellType.STRING && isBlank(cell
.getStringCellValue()))) {
return null;
}
CellType cellType = cell.getCellTypeEnum();
if(cellType == CellType.BLANK)
return null;
else if(cellType == CellType.BOOLEAN)
return cell.getBooleanCellValue();
else if(cellType == CellType.ERROR)
return cell.getErrorCellValue();
else if(cellType == CellType.FORMULA) {
try {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue();
} else {
return cell.getNumericCellValue();
}
} catch (IllegalStateException e) {
return cell.getRichStringCellValue();
}
}
else if(cellType == CellType.NUMERIC){
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue();
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
return cell.getStringCellValue();
}
}
else if(cellType == CellType.STRING)
return cell.getStringCellValue();
else
return null;
}
private static boolean isBlank(String str){
if(str == null){
return true;
}
return str.length() == 0;
}
public static void main(String[] args) throws IOException {
ExcelUtil excelUtils = new ExcelUtil();
Map<String,String> header = new LinkedHashMap<>();
header.put("name","姓名");
header.put("age","年龄");
header.put("birthday","出生日期");
header.put("sex","性别");
List<Map<String,Object>> list = new ArrayList<>();
Map<String,Object> map1 =new LinkedHashMap<>();
map1.put("name", "张伟");
map1.put("age", 12);
map1.put("birthday", "2016/5/7");
map1.put("sex", "男");
Map<String,Object> map2 =new LinkedHashMap<>();
map2.put("name", "Tom");
map2.put("age", 24);
map2.put("birthday", "2016/9/7");
map2.put("sex", "女");
for (int i = 0; i < 100; i++) {
list.add(map1);
list.add(map2);
}
File f= new File("src/main/resources/excel/test.xlsx");
OutputStream out = new FileOutputStream(f);
excelUtils.exportToExcel(header,list, out);
String path = "D:\\demo\\utils\\src\\main\\resources\\excel\\test.xlsx";
File file = new File(path);
InputStream inputStream = new FileInputStream(file);
ArrayList<HashMap<String, Object>> data = excelUtils.importFromExcel(inputStream);
for (int i = 0; i < data.size(); i++) {
for (String key : data.get(i).keySet()) {
System.out.println(data.get(i).get(key));
}
}
System.out.println("完成");
out.close();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异