import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.FileHeader;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* @author huangxijian
*/
public class SimpleFileUtil {
private static Logger logger = LoggerFactory.getLogger(SimpleFileUtil.class);
/**
* 将文件转换成byte[]
*
* @param filePath 文件路径
* @author sjl
*/
public static byte[] fileToBytes(String filePath) {
try (FileInputStream fis = new FileInputStream(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] b = new byte[10];
int len;
while ((len = fis.read(b)) != -1) {
bos.write(b, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("fileToBytes异常,异常信息:", e);
}
}
/**
* 将文件转换成String字符串
*
* @param filePath 文件路径
* @author sjl
*/
public static String fileToString(String filePath) {
try (FileInputStream fis = new FileInputStream(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
bos.write(b, 0, len);
}
return bos.toString();
} catch (IOException e) {
throw new RuntimeException("fileToString异常,异常信息", e);
}
}
/**
* 将byte[]压缩成zip
*
* @param zipPath zip路径
*/
public static void zip(String zipPath, String filename, byte[] data) {
try (FileOutputStream bos = new FileOutputStream(zipPath);
ZipOutputStream zip = new ZipOutputStream(bos)) {
ZipEntry entry = new ZipEntry(filename);
entry.setSize(data.length);
zip.putNextEntry(entry);
zip.write(data);
zip.closeEntry();
} catch (Exception ex) {
throw new RuntimeException("zip异常,异常信息", ex);
}
}
/**
* 将文件压缩成zip
*
* @param zipPath zip路径
* @param filePath 文件路径
*/
public static void zipByFile(String zipPath, String filePath) {
zipByFile(zipPath, null, filePath);
}
/**
* 将文件压缩成zip
*
* @param zipPath zip路径
* @param filename 文件名
* @param filePath 文件路径
*/
public static void zipByFile(String zipPath, String filename, String filePath) {
// 命名
File file = new File(filePath);
if (filename == null || (StrUtil.EMPTY).equals(filename)) {
filename = file.getName();
}
// 创建路径
File zipFile = new File(zipPath);
if (!zipFile.getParentFile().exists() && !zipFile.getParentFile().mkdirs()) {
throw new RuntimeException("无法创建目录,目录路径为:" + zipFile.getParent());
}
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile))) {
ZipEntry entry = new ZipEntry(filename);
zip.putNextEntry(entry);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = bis.read(bytes)) != -1) {
zip.write(bytes, 0, len);
}
} catch (Exception ex) {
throw new RuntimeException("zip异常,异常信息", ex);
}
}
/**
* 将目录下所有文件压缩成zip
*
* @param zipPath zip路径
* @param dirPath 文件目录
*/
public static void zipByDir(String zipPath, String dirPath) {
List<File> fileList = getFileList(dirPath);
if (CollectionUtils.isEmpty(fileList)) {
return;
}
// 创建路径
File zip = new File(zipPath);
if (!zip.getParentFile().exists() && !zip.getParentFile().mkdirs()) {
throw new RuntimeException("无法创建目录,目录路径为:" + zip.getParent());
}
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath))) {
for (File file : fileList) {
System.out.println(file.getPath());
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
ZipEntry entry = new ZipEntry(file.getAbsolutePath().replace(dirPath, StrUtil.EMPTY));
zos.putNextEntry(entry);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = bis.read(bytes)) != -1) {
zos.write(bytes, 0, len);
}
} catch (Exception ex) {
throw new RuntimeException("将目录下所有文件压缩成zip 异常,异常信息", ex);
}
}
} catch (Exception e) {
throw new RuntimeException("将目录下所有文件压缩成zip异常", e);
}
}
/**
* 将目录下所有文件压缩成zip
*
* @param zipPath zip路径
* @param fileList 文件
*/
public static void zipByFileList(String zipPath, List<File> fileList) {
// 创建路径
File zip = new File(zipPath);
if (!zip.getParentFile().exists() && !zip.getParentFile().mkdirs()) {
throw new RuntimeException("无法创建目录,目录路径为:" + zip.getParent());
}
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath))) {
for (File file : fileList) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = bis.read(bytes)) != -1) {
zos.write(bytes, 0, len);
}
} catch (Exception ex) {
throw new RuntimeException("将所有文件压缩成zip 异常,异常信息", ex);
}
}
} catch (Exception e) {
throw new RuntimeException("将所有文件压缩成zip异常", e);
}
}
public static List<File> getFileList(String dirPath) {
List<File> fileList = new ArrayList<>();
File file = new File(dirPath);
File[] tempList = file.listFiles();
if (tempList == null || tempList.length == 0) {
return fileList;
}
for (File value : tempList) {
if (value.isFile()) {
fileList.add(value);
}
if (value.isDirectory()) {
fileList.addAll(getFileList(value.getAbsolutePath()));
}
}
return fileList;
}
/**
* 将zip解压
*
* @param zipBytes 字节
* @param outPath 输出路径
*/
public static List<String> unzipByByte(byte[] zipBytes, String outPath) {
try (ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(zipBytes));
BufferedInputStream bin = new BufferedInputStream(zin)) {
return doUnzip(outPath, zin, bin);
} catch (IOException fe) {
throw new RuntimeException("unzip异常,异常信息", fe);
}
}
/**
* 将zip解压
*
* @param zipPath zip路径
* @param outDir 输出路径
*/
public static List<String> unzip(String zipPath, String outDir) {
Charset charset = simpleRecognizeCharset(new File(zipPath));
logger.info("zip的编码格式为:{}", charset.name());
try (ZipInputStream zin = new ZipInputStream(new FileInputStream(zipPath), charset);
BufferedInputStream bin = new BufferedInputStream(zin)) {
return doUnzip(outDir, zin, bin);
} catch (IOException fe) {
throw new RuntimeException("unzip异常,异常信息", fe);
}
}
/**
* 将zip解压
*
* @param zipFile zip文件
* @param outDir 输出路径
*/
public static List<String> unzip(File zipFile, String outDir) {
Charset charset = simpleRecognizeCharset(zipFile);
logger.info("zip的编码格式为:{}", charset.name());
try (ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile), charset);
BufferedInputStream bin = new BufferedInputStream(zin)) {
return doUnzip(outDir, zin, bin);
} catch (IOException fe) {
throw new RuntimeException("unzip异常,异常信息", fe);
}
}
/**
* 将zip解压
*
* @param inputStream 输入流
* @param outPath 输出路径
*/
public static List<String> unzip(InputStream inputStream, String outPath) {
try (ZipInputStream zin = new ZipInputStream(inputStream);
BufferedInputStream bin = new BufferedInputStream(zin)) {
return doUnzip(outPath, zin, bin);
} catch (IOException fe) {
throw new RuntimeException("unzip异常,异常信息", fe);
}
}
/**
* 将RPA的zip解压
*
* @param zipPath zip路径
* @param outpath 输出路径
*/
public static void unzipRPAFile(String zipPath, String outpath) throws IOException {
try (ZipInputStream zin = new ZipInputStream(new FileInputStream(zipPath), Charset.forName("GBK"));
BufferedInputStream Bin = new BufferedInputStream(zin)) {
doUnzip(outpath, zin, Bin);
} catch (FileNotFoundException e) {
throw new RuntimeException("unzipRPAFile异常,异常信息", e);
}
}
private static List<String> doUnzip(String outDir, ZipInputStream zin, BufferedInputStream bin) throws IOException {
List<String> pathList = new ArrayList<>();
//输入源zip路径
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
// 如果是目录 重新开始
if (StrUtil.isBlank(entry.getName()) || entry.isDirectory()) {
continue;
}
// 如果是MAC额外文件缩略图 重新开始
if (entry.getName().contains("__MACOSX")) {
continue;
}
File fout = new File(outDir, entry.getName());
if (!fout.getParentFile().exists() && !fout.getParentFile().mkdirs()) {
// 如果原格式名字过长 起临时名
fout = new File(outDir, System.currentTimeMillis() + File.separator + FileUtil.getName(entry.getName()));
if (!fout.getParentFile().exists() && !fout.getParentFile().mkdirs()) {
throw new RuntimeException("无法创建目录,目录路径为:" + fout.getParent());
}
}
try (BufferedOutputStream Bout = new BufferedOutputStream(new FileOutputStream(fout))) {
int len;
byte[] bytes = new byte[1024];
while ((len = bin.read(bytes)) != -1) {
Bout.write(bytes, 0, len);
}
} catch (IOException e) {
throw new RuntimeException("unzip异常,异常信息", e);
}
pathList.add(fout.getAbsolutePath());
}
return pathList;
}
/**
* 根据时间生成临时文件名称
*
* @return 文件名
*/
public static String buildTempName() {
Calendar c = Calendar.getInstance();
Date date = c.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String sCurTime = sdf.format(date);
// 产生100000到999999的随机数
long temp = Math.round(Math.random() * 899999 + 100000);
return sCurTime + temp;
}
/**
* 根据byte数组,生成文件
*
* @param bfile
* @param filePath
* @param fileName
* @return void
*/
public static void getFile(byte[] bfile, String filePath, String fileName) {
File file = new File(filePath, fileName);
// 判断文件目录是否存在
if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
throw new RuntimeException("无法创建目录,目录路径为:" + filePath);
}
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
bos.write(bfile);
} catch (IOException e) {
throw new RuntimeException("getFile异常,异常信息", e);
}
}
/**
* 批量删除
*/
public static void deleteFileByPathList(Collection<String> collection) {
if (CollectionUtils.isNotEmpty(collection)) {
for (String path : collection) {
deleteFileByPath(path);
}
}
}
/**
* 单个删除
*/
public static void deleteFileByPath(String filePath) {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
}
/**
* 识别编码方式
*
* @param file 文件路径
* @return 编码方式,默认GBK,当前Windows用户还是偏多
*/
public static Charset recognizeCharset(File file) {
try (ZipFile zipFile = new ZipFile(file)) {
zipFile.setCharset(Charset.forName("GBK"));
List<FileHeader> fileHeaders = zipFile.getFileHeaders();
if (fileHeaders == null || fileHeaders.isEmpty()) {
return Charset.forName("GBK");
}
// 只识别空白符、英文大小写字母、数字、下划线、点、中文、反斜杠
// 其他需要识别的字符需要自己扩充
// 标点符号\pP|\pS暂不识别
String messyRegex = "[\\sa-zA-Z_0-9./\u4e00-\u9fa5]+";
for (FileHeader fileHeader : fileHeaders) {
String fileName = fileHeader.getFileName();
if (!fileName.matches(messyRegex)) {
// 存在乱码,使用UTF8
return StandardCharsets.UTF_8;
}
}
return Charset.forName("GBK");
} catch (Exception e) {
logger.error("zip文件读取错误,取默认编码gbk", e);
return Charset.forName("GBK");
}
}
/**
* 识别编码方式
*
* @param file 文件路径
* @return 编码方式,默认GBK,当前Windows用户还是偏多
*/
public static Charset simpleRecognizeCharset(File file) {
try (ZipInputStream zin = new ZipInputStream(new FileInputStream(file), Charset.forName("GBK"))) {
while (zin.getNextEntry() != null) {
// do nothing
}
return Charset.forName("GBK");
} catch (Exception e) {
return StandardCharsets.UTF_8;
}
}
public static List<String> readLines(String filePath) {
return FileUtil.readLines(filePath, "UTF-8");
}
public static void main(String[] args) throws FileNotFoundException {
File file = new File("D:\\test\\123.txt");
List<String> lineList = FileUtil.readLines(file, "UTF-8");
lineList.forEach(System.out::println);
}
}
File 常用功能
于 2024-10-11 17:49:47 首次发布