保持更新ing…
package com.unitechs.rest.util;
import com.unitechs.framework.logger.Logger;
import com.unitechs.framework.logger.LoggerFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 通用的文件操作工具类
*/
public class FileUtil {
private static final int BUFFER_SIZE = 1024;
/**
* 递归zip
*
* @param zipOut
* @param fileName
* @throws IOException
*/
public static void zip(ZipOutputStream zipOut, String fileName)
throws IOException {
File srcFileName = new File(fileName);
if (srcFileName.isDirectory()) {
// 如果是文件夹,遍历下面的文件
File[] files = srcFileName.listFiles();
for (File file : files) {
zip(zipOut, file.getAbsolutePath());
}
} else {
// 创建文件输入流对象
String encode = "ISO8859_1";
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(srcFileName), encode));
// 创建指向压缩原始文件的入口
ZipEntry entry = new ZipEntry(srcFileName.getName());
zipOut.putNextEntry(entry);
// 向压缩文件中输出数据
int nNumber;
while ((nNumber = in.read()) != -1) {
zipOut.write(nNumber);
}
in.close();
}
}
/**
* 由于java.util.zip.ZipOutputStream有中文乱码问题,
* 所以采用org.apache.tools.zip.ZipOutputStream。
*/
public static void zip(String zipFileName, String srcFileName) throws IOException {
ZipOutputStream zipOut = null;
try {
// 创建文件输出流对象
FileOutputStream f = new FileOutputStream(new File(zipFileName));
CheckedOutputStream ch = new CheckedOutputStream(f, new CRC32());
// 创建ZIP数据输出流对象
zipOut = new ZipOutputStream(new BufferedOutputStream(ch));
// 调用打包的方法
zip(zipOut, srcFileName);
} finally {
if (zipOut != null) zipOut.close();
}
}
/**
* 获取文件内容
*
* @param path 文件路径
* @return 文件内容
*/
public static String getFileContent(String path) {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(path));
String line;
String lineSeparator = System.lineSeparator();
while ((line = br.readLine()) != null) {
sb.append(line).append(lineSeparator);
}
} catch (IOException e) {
log.error("获取" + path + "文件内容失败:", e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
}
}
}
return sb.toString();
}
/**
* 创建文件
*
* @param fileName 文件名
* @param fileContent 文件内容
*/
public static void createFile(String fileName, String fileContent) {
RandomAccessFile mneRaf = null;
FileChannel mneChannel = null;
ByteBuffer byteBuffer = null;
try {
mneRaf = new RandomAccessFile(fileName, "rw");
mneChannel = mneRaf.getChannel();
byteBuffer = ByteBuffer.allocate(fileContent.getBytes().length);
byteBuffer.put(fileContent.getBytes());
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
mneChannel.write(byteBuffer);
}
} catch (IOException e) {
log.error(e);
} finally {
if (byteBuffer != null) {
byteBuffer.clear();
}
try {
if (mneRaf != null) {
mneRaf.close();
}
} catch (IOException e) {
log.error(e);
}
try {
if (mneChannel != null) {
mneChannel.close();
}
} catch (IOException e) {
log.error(e);
}
}
}
/**
* 修改tar包中的文件名,需要传入 源文件名及对应的目标文件名map
* 会破坏原有的目录结构,不会保留子文件夹目录,只会提取其中文件
* @param sourcedir
* @param targetdir
* @param nameMap
* @throws IOException
*/
public static void modifyTarGzFileName(String sourcedir, String targetdir, Map<String, String> nameMap) throws IOException {
Path sourcePath = Paths.get(sourcedir);
Path targetPath = Paths.get(targetdir);
if (!Files.exists(sourcePath)) {
throw new IllegalArgumentException("源文件不存在");
}
if (!Files.isRegularFile(sourcePath)) {
throw new IllegalArgumentException("源路径不是一个文件");
}
if (!Files.exists(targetPath)) {
Files.createFile(targetPath);
}
// 处理 .tar.gz 文件流
try (InputStream fi = Files.newInputStream(sourcePath);
BufferedInputStream bi = new BufferedInputStream(fi);
TarArchiveInputStream tarIs = new TarArchiveInputStream(bi);
OutputStream fo = Files.newOutputStream(targetPath);
BufferedOutputStream bo = new BufferedOutputStream(fo);
TarArchiveOutputStream tarOs = new TarArchiveOutputStream(bo)) {
TarArchiveEntry entry;
while ((entry = tarIs.getNextTarEntry()) != null) {
if (entry.isDirectory()){
continue;
}
// 修改文件名称,如果映射存在
String entryName = entry.getName();
String[] split = StringUtils.split(entryName, "/");
entryName = split[split.length - 1];
String newName = nameMap.getOrDefault(entryName, entryName);
TarArchiveEntry newEntry = new TarArchiveEntry(newName);
newEntry.setSize(entry.getSize());
tarOs.putArchiveEntry(newEntry);
// 复制数据
IOUtils.copy(tarIs, tarOs);
tarOs.closeArchiveEntry();
}
}
}
/**
* tar文件转zip
* @param sourceTarGzPath
* @param targetZipPath
* @throws IOException
*/
public static void tarGzToZip(String sourceTarGzPath, String targetZipPath) throws IOException {
if (!Files.exists(Paths.get(sourceTarGzPath))) {
throw new IllegalArgumentException("源文件不存在");
}
if (!Files.isRegularFile(Paths.get(sourceTarGzPath))) {
throw new IllegalArgumentException("源路径不是一个文件");
}
if (!Files.exists(Paths.get(targetZipPath))) {
Files.createFile(Paths.get(targetZipPath));
}
// 通过InputStream读取文件
FileInputStream fis = new FileInputStream(sourceTarGzPath);
BufferedInputStream bis = new BufferedInputStream(fis);
TarArchiveInputStream tarIs = new TarArchiveInputStream(bis);
// 创建一个ZipOutputStream来写入zip文件
FileOutputStream fos = new FileOutputStream(targetZipPath);
ZipOutputStream zipOs = new ZipOutputStream(fos);
TarArchiveEntry tarEntry;
byte[] buffer = new byte[1024];
int count;
// 遍历tar.gz文件中的每个条目,并将它们添加到zip文件中
while ((tarEntry = tarIs.getNextTarEntry()) != null) {
// 如果是文件,添加到zip文件
if (!tarEntry.isDirectory()) {
// 以数字为名称创建文件,您也可以选择其他命名方案
String entryName = tarEntry.getName();
ZipEntry zipEntry = new ZipEntry(entryName);
zipOs.putNextEntry(zipEntry);
// 读取tar条目数据并写入zip条目
while ((count = tarIs.read(buffer)) != -1) {
zipOs.write(buffer, 0, count);
}
// 关闭当前zip条目
zipOs.closeEntry();
}
}
// 关闭流
zipOs.close();
tarIs.close();
bis.close();
fis.close();
}
/**
* 解压tar包到指定目录 目录名称不能包含特殊字符
* @param tarFilePath
* @param outputDirPath
* @throws Exception
*/
public static void extractTarFile(String tarFilePath, String outputDirPath) throws Exception {
File tarFile = new File(tarFilePath);
File outputDir = new File(outputDirPath);
if (!tarFile.exists()) {
throw new IllegalArgumentException("Tar file does not exist: " + tarFilePath);
}
// 确保输出目录存在
if (!outputDir.exists()) {
outputDir.mkdirs();
}
try (TarArchiveInputStream tarIn = new TarArchiveInputStream(new FileInputStream(tarFile))) {
TarArchiveEntry entry;
// 遍历tar包中的每个条目
while ((entry = tarIn.getNextTarEntry()) != null) {
// 处理文件和目录
if (entry.isDirectory()) {
// 创建目录
new File(outputDir, entry.getName()).mkdirs();
} else {
// 写出文件到指定目录
File outputFile = new File(outputDir, entry.getName());
// 如果文件额上级目录不存在,则创建该目录
outputFile.getParentFile().mkdirs();
// 写出文件内容
try (OutputStream outputFileStream = new FileOutputStream(outputFile)) {
IOUtils.copy(tarIn, outputFileStream);
}
}
}
}
}
/**
* 将Byte数组转换成文件
* @param bytes byte数组
* @param file 文件
*/
public static void fileToBytes(byte[] bytes, File file) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
if (!file.getParentFile().exists()) {
//文件夹不存在 生成
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 创建一个文件, 将字符串写入文件
*/
public static void createFileWriteIn(String fileName, String fileContent) {
RandomAccessFile mneRaf = null;
FileChannel mneChannel = null;
ByteBuffer byteBuffer = null;
try {
mneRaf = new RandomAccessFile(fileName, "rw");
mneChannel = mneRaf.getChannel();
byteBuffer = ByteBuffer.allocate(fileContent.getBytes().length);
byteBuffer.put(fileContent.getBytes());
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
mneChannel.write(byteBuffer);
}
} catch (IOException e) {
logger.error(e);
} finally {
if (byteBuffer != null) {
byteBuffer.clear();
}
try {
if (mneRaf != null) {
mneRaf.close();
}
} catch (IOException e) {
logger.error(e);
}
try {
if (mneChannel != null) {
mneChannel.close();
}
} catch (IOException e) {
logger.error(e);
}
}
}
/**
* 监听一个文件夹 , 在创建一个新的文件夹后就停止该监听器 返回文件夹的路径(可扩展 包括新建一个文件/删除一个文件之类的操作)
*/
public static String monitorPathCreateDir(String absPath) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
FileListener fileListener = new FileListener(){
@Override
public void onDirectoryCreate(File directory) {
super.onDirectoryCreate(directory);
latch.countDown();
}
};
FileAlterationObserver fileAlterationObserver = new FileAlterationObserver(new File(absPath));
FileAlterationMonitor fileAlterationMonitor = new FileAlterationMonitor(1000);
fileAlterationObserver.addListener(fileListener);
fileAlterationMonitor.addObserver(fileAlterationObserver);
fileAlterationMonitor.start();
latch.await();
fileAlterationMonitor.stop();
return fileListener.getLatestDirectory();
}
}
文件监听类
public class FileListener extends FileAlterationListenerAdaptor {
private String latestDirectory;
public String getLatestDirectory() {
return latestDirectory;
}
@Override
public void onStart(FileAlterationObserver observer) {
super.onStart(observer);
}
@Override
public void onDirectoryCreate(File directory) {
latestDirectory = directory.getAbsolutePath();
}
@Override
public void onDirectoryChange(File directory) {
}
@Override
public void onDirectoryDelete(File directory) {
}
@Override
public void onFileCreate(File file) {
}
@Override
public void onFileChange(File file) {
}
@Override
public void onFileDelete(File file) {
}
@Override
public void onStop(FileAlterationObserver observer) {
super.onStop(observer);
}
}