代码
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.jar.JarArchiveEntry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Auther: liyue
* @Date: 2019/4/12 19:44
* @Description: 文件工具类
*/
public class FileUtil {
/**
* 按行读取
*
* @param path
* @return String
*/
public static String readByLineRs(String path) {
StringBuffer sb = new StringBuffer();
File file = new File(path);
BufferedReader reader = null;
String temp = null;
try {
reader = new BufferedReader(new FileReader(file));
while ((temp = reader.readLine()) != null) {
sb.append(temp).append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
/*
* <目录>
* 1.删除文件或者文件夹
* 2.解压zip文件
* 3.根据多个file对象压缩文件
* 4.根据文件全路径名压缩文件
* 5.解压rar文件
* 6.按行读取文件
* 7.按行读取文件(参数为文件全路径名)
* 8.按行读取文件(参数为file对象)
* 9.字符流写入文件
* 10.字符流追加写入文件
*/
public static void main(String[] args) {
unRar("/Users/leyili/Desktop/file_test/test1.rar", "/Users/leyili/Desktop/file_test/test2", Boolean.FALSE);
}
/**
* 删除文件或者文件夹
*
* @param file
* @return
*/
public static boolean delFile(File file) {
if (!file.exists()) {
return false;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
delFile(f);
}
}
return file.delete();
}
/**
* 解压zip文件
*
* @param warPath zip文件路径
* @param unzipPath 保存路径
*/
public static void unzip(String warPath, String unzipPath) {
File warFile = new File(warPath);
try {
//获得输出流
BufferedInputStream bufferedInputStream = new BufferedInputStream(
new FileInputStream(warFile));
ArchiveInputStream in = new ArchiveStreamFactory()
.createArchiveInputStream(ArchiveStreamFactory.JAR,
bufferedInputStream);
JarArchiveEntry entry = null;
//循环遍历解压
while ((entry = (JarArchiveEntry) in.getNextEntry()) != null) {
if (entry.getName().indexOf("__MACOSX") != -1)
continue;
if (entry.isDirectory()) {
new File(unzipPath, entry.getName()).mkdir();
} else {
OutputStream out = FileUtils.openOutputStream(new File(
unzipPath, entry.getName()));
IOUtils.copy(in, out);
out.close();
}
}
in.close();
} catch (FileNotFoundException e) {
System.err.println("未找到war文件");
} catch (ArchiveException e) {
System.err.println("不支持的压缩格式");
} catch (IOException e) {
System.err.println("文件写入发生错误");
}
}
/**
* 根据多个file对象压缩文件
*
* @param srcFiles 文件对象列表
* @param zipFile 压缩之后的文件名
* @param isDelete 是否删除原文件
*/
public static void zipFiles(File[] srcFiles, File zipFile, Boolean isDelete) {
// 判断压缩后的文件存在不,不存在则创建
if (!zipFile.exists()) {
try {
zipFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 创建 FileOutputStream 对象
FileOutputStream fileOutputStream = null;
// 创建 ZipOutputStream
ZipOutputStream zipOutputStream = null;
// 创建 FileInputStream 对象
FileInputStream fileInputStream = null;
try {
// 实例化 FileOutputStream 对象
fileOutputStream = new FileOutputStream(zipFile);
// 实例化 ZipOutputStream 对象
zipOutputStream = new ZipOutputStream(fileOutputStream);
// 创建 ZipEntry 对象
ZipEntry zipEntry = null;
// 遍历源文件数组
for (int i = 0; i < srcFiles.length; i++) {
// 将源文件数组中的当前文件读入 FileInputStream 流中
fileInputStream = new FileInputStream(srcFiles[i]);
// 实例化 ZipEntry 对象,源文件数组中的当前文件
zipEntry = new ZipEntry(srcFiles[i].getName());
zipOutputStream.putNextEntry(zipEntry);
// 该变量记录每次真正读的字节个数
int len;
// 定义每次读取的字节数组
byte[] buffer = new byte[1024];
while ((len = fileInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
}
zipOutputStream.closeEntry();
zipOutputStream.close();
fileInputStream.close();
fileOutputStream.close();
if (isDelete) {
for (int i = 0; i < srcFiles.length; i++) {
srcFiles[i].delete();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据文件全路径名压缩文件
*
* @param filePaths 文件全路径名称列表
* @param zipFile 压缩之后的文件名
* @param isDelete 是否删除原文件
*/
public static void zipFiles(List<String> filePaths, File zipFile, Boolean isDelete) {
File[] srcFiles = new File[filePaths.size()];
for (int i = 0; i < filePaths.size(); i++) {
srcFiles[i] = new File(filePaths.get(i));
}
zipFiles(srcFiles, zipFile, isDelete);
}
/**
* 解压rar文件
*
* @param file
* @param outDir
* @param alikePath 所有解压文件是否都放在解压目录
* @throws Exception
*/
public static void unRar(String file, String outDir, Boolean alikePath) {
try {
File rarFile = new File(file);
File outFileDir = new File(outDir);
if (!outFileDir.exists()) {
outFileDir.mkdirs();
}
Archive archive = new Archive(new FileInputStream(rarFile));
FileHeader fileHeader = archive.nextFileHeader();
while (fileHeader != null) {
String fileName = fileHeader.getFileNameW();
if (fileName == null || fileName.equals(""))
fileName = fileHeader.getFileNameString();
fileName = fileName.replaceAll(" ", "");
if (fileHeader.isDirectory()) {
if (!alikePath)
new File(outDir + fileName).mkdirs();
fileHeader = archive.nextFileHeader();
continue;
}
if (alikePath) {
if (fileName.indexOf("\\") != -1)
fileName = fileName.split("\\\\")[1];
}
File out = null;
if (!alikePath) {
out = new File(outDir + fileName.replace("\\", "/"));
} else {
out = new File(outDir + fileName.split("\\\\")[0]);
}
if (!out.exists()) {
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
out.createNewFile();
}
FileOutputStream os = new FileOutputStream(out);
archive.extractFile(fileHeader, os);
os.close();
fileHeader = archive.nextFileHeader();
}
archive.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
/**
* 按行读取文件(参数为文件全路径名)
*
* @param readHead 是否读取第一行
* @param filePath
* @return
*/
public static List<List<String>> read(Boolean readHead, String filePath) {
List<List<String>> lists = new LinkedList<>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)),
"GBK"));
String lineTxt = null;
int index = 0;
while ((lineTxt = br.readLine()) != null) {
index++;
if (!readHead) {
if (index == 1)
continue;
}
String[] strings = lineTxt.split("\t");
List<String> list = new LinkedList<>();
for (String string : strings) {
list.add(string);
}
lists.add(list);
}
br.close();
} catch (Exception e) {
}
return lists;
}
/**
* 按行读取文件(参数为file对象)
*
* @param readHead 是否读取第一行
* @param file
* @return
*/
public static List<List<String>> read(Boolean readHead, File file) {
List<List<String>> lists = new LinkedList<>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),
"GBK"));
String lineTxt = null;
int index = 0;
while ((lineTxt = br.readLine()) != null) {
index++;
if (!readHead) {
if (index == 1)
continue;
}
String[] strings = lineTxt.split("\t");
List<String> list = new LinkedList<>();
for (String string : strings) {
list.add(string);
}
lists.add(list);
}
br.close();
} catch (Exception e) {
}
return lists;
}
/**
* 字符流写入文件
*
* @param content
* @param path
*/
public static void writeString(String content, String path) {
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 字符流追加写入文件
*
* @param conent
* @param path
*/
public static void writeStringAppend(String conent, String path) {
BufferedWriter out = null;
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path, true)));
out.write(conent + "\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
maven
<!-- Apache Commons Compress 用于处理多种归档文件格式 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.24.0</version>
</dependency>
<!-- Apache Commons IO 提供了 IO 操作的工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>7.5.5</version>
</dependency>
END。