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;
/**
* @创建人 jiangchun
* @创建时间 2019/8/22
* @描述 用于操作文件 把文件内容读取为一个字符串,把字符串转储为文件,读取某目录下所有文件
*/
@Slf4j
public class FileUtil {
private ArrayList<String> data = new ArrayList<>();
/**
* @描述 读取文件为字符串
* @参数 path 文件路径
* @返回值 String 文件内容
*/
public String fileRead(String path) throws Exception {
File file = new File(path);//定义一个file对象,用来初始化FileReader
FileReader reader = new FileReader(file);//定义一个fileReader对象,用来初始化BufferedReader
BufferedReader bReader = new BufferedReader(reader);//new一个BufferedReader对象,将文件内容读取到缓存
StringBuilder sb = new StringBuilder();//定义一个字符串缓存,将字符串存放缓存中
String s = "";
while ((s =bReader.readLine()) != null) {//逐行读取文件内容,不读取换行符和末尾的空格
sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
//System.out.println(s);
}
bReader.close();
String str = sb.toString();
return str;
}
/**
* @描述 读取文件为字符串
* @参数 ptah 文件路径
* @返回值 String 文件内容
*/
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 ;
}
/**
* @描述 字符串保存为文件
* @参数 strFilename 文件名包括后缀
* @参数 strBuffer 字符串,将保存到文件
* @返回值 空
*/
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();
}
}
/**
* @描述 递归获取某路径下的所有文件
* @参数 path 指定路径
* @返回值 ArrayList<String> 字符串集合保存路径下的所有文件(绝对路径) 如d:/test/test.txt
*/
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()) {
//log.info("目录:" + files[i].getPath());
getFiles(files[i].getPath());
} else {
//log.info("文件:" + files[i].getPath());
data.add(files[i].getPath());
}
}
} else {
//log.info("文件:" + file.getPath());
}
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;
}
}
/**
* 判断指定的文件是否存在。
*
* @param fileName
* @return
*/
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();
/*try {
String content = fileUtil.fileRead("D:\\demo\\utils\\src\\main\\resources\\file\\test.txt");
System.out.println(content);
} catch (Exception e) {
e.printStackTrace();
}
try {
String content = fileUtil.getTemplateContent("D:\\demo\\utils\\src\\main\\resources\\file\\test.txt");
System.out.println(content);
fileUtil.TextToFile("D:\\demo\\utils\\src\\main\\resources\\file\\testCopy.txt",content);
} catch (Exception e) {
e.printStackTrace();
}
List files = fileUtil.getFiles("D:\\demo\\utils\\src\\main\\resources");
System.out.println(files);*/
/*if (fileUtil.delAll("D:\\demo\\utils\\src\\main\\resources\\file\\delAll")) {
System.out.println("删除成功");
}*/
/*if (fileUtil.createDir("D:\\AAA\\test\\hello")) {
System.out.println("创建成功");
}else {
System.out.println("创建失败");
}
if (fileUtil.createFile("D:\\AAA\\BB\\test.txt")) {
System.out.println("创建文件成功");
} else {
System.out.println("创建文件失败");
}*/
if (fileUtil.isFileExist("D:\\AAA\\BB\\test.txt")) {
System.out.println("存在");
}
if (fileUtil.deleteFile("D:\\AAA\\BB\\test.txt")) {
System.out.println("删除成功");
}
}
}
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.*;
/**
* @创建人 jiangchun
* @创建时间 2019/8/22
* @描述 用于操作excel xlsx版
*/
public class ExcelUtil {
/*从excel中导入到内存*/
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;
}
/*从内存导出到excel*/
public <T> void exportToExcel(Map<String,String> headers, List<T> dataset, OutputStream out) {
//时间格式默认"yyyy-MM-dd"
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();
}
}
原文:https://www.cnblogs.com/ltspring/p/11750334.html