提示:常用的文件操作工具类
前言
常用的文件操作工具类:
包括文件,目录树的拷贝、删除、移动、查找等工具
开发过程中文件操作基本必不可少,常用的就是拷贝移动删除等,本案例还包含了打包,文件写入等
提示:以下是本篇文章正文内容,下面案例可供参考
1.代码示例
代码如下(示例):
public class FileTool {
/**
* 复制单个文件。源和目标必须都是文件,不能是目录。
*
* @param src 源文件。
* @param dest 目标文件。
* @param cover true表示如果目标文件存在则覆盖,false表示如果目标文件存在则抛出异常。
*/
public static void copy(File src, File dest, boolean cover, String parType)
throws IOException {
src = handleFile(src, parType);
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
byte[] buf = new byte[1024];
try {
int i;
while ((i = fis.read(buf)) >= 0) {
fos.write(buf, 0, i);
}
} finally {
try {
fis.close();
} catch (Exception ex) {
}
try {
fos.close();
} catch (Exception ex) {
}
}
}
public static void copy(File src, File dest, boolean cover) throws IOException {
copy(src, dest, cover, null);
}
/**
* 复制目录树。
* 如果源和目标都是目录,则将源目录里的文件拷贝到目标目录里;
* 如果源是文件目标是目录,则将源拷贝到目标目录里面;
* 如果源是目录而目标是文件,则抛异常;
* 如果源和目标都是文件,则用源文件覆盖目标文件;
* 如果源是文件而目标不存在,则在目标位置创建文件;
* 如果源是目录而目标不存在,则以目标名称建立目录,并将源目录里内容拷贝至目标目录下。
* 如果源不存在,则抛异常。
*
* @param src 源文件或目录。
* @param dest 目的文件或目录。
* @param cover 目的文件存在是否覆盖,若是false则遇到该覆盖文件时将抛异常。
*/
public static void copytree(File src, File dest, boolean cover, String parType)
throws IOException {
if (src.isFile()) {
copy(src, dest, cover, parType);
} else { // src是目录或不存在
File[] children = src.listFiles(); //若src不存在这里会抛异常
for (int i = 0; i < children.length; i++) {
File f = new File(dest, children[i].getName());
if (children[i].isDirectory()) { //对于src的每个子目录
f.mkdirs(); //创建目标子目录,如果已经存在则会忽略
copytree(children[i], f, cover, parType); //递归
} else { //对于src下每个文件
copy(children[i], f, cover, parType);
}
}
}
}
public static void copytree(File src, File dest, boolean cover)
throws IOException {
copytree(src, dest, cover, null);
}
/**
* 复制目录树。
* 如果源和目标都是目录,则将源目录里的文件拷贝到目标目录里;
* 如果源是文件目标是目录则将源拷贝到目标目录里面;
* 如果源是目录而目标是文件,则抛异常;
* 如果源和目标都是文件则用源文件覆盖目标文件;
* 如果源是文件而目标不存在则在目标位置创建文件;
* 如果源是目录而目标不存在则在以目标名称建立目录并将源目录里内容拷贝至目标目录下。
* 如果源不存在则抛异常。
*
* @param src 源文件或目录。
* @param dest 目的文件或目录。
* @param cover 目的文件存在是否覆盖,若是false则遇到该覆盖文件时将抛异常。
*/
public static void movetree(File src, File dest, boolean cover) throws IOException {
copytree(src, dest, cover, null);
deltree(src);
}
/**
* 删除文件或整个目录树。
*
* @param f 文件或目录。
*/
public static void deltree(File f) {
File[] children = f.listFiles();
if (children != null && children.length != 0) {
for (int i = 0; i < children.length; i++) {
deltree(children[i]);
}
}
f.delete();
}
/**
* 在一个目录及其子目录下查找符合条件的文件或目录。
*
* @param filter 文件过滤条件。该接口的accept方法如果返回true则中止查找,否则继续查找,
* 对文件的处理请在该接口的accept()方法里完成。
* @param root 查找开始的位置。
* @return 是否找到。
*/
public static boolean find(File root, FileFilter filter) {
if (filter.accept(root)) {
return true;
} else {
File[] children = root.listFiles();
if (children == null || children.length == 0) {
return false;
} else {
for (int i = 0; i < children.length; i++) {
if (find(children[i], filter)) {
return true;
}
}
return false;
}
}
}
/**
* 文件填充数据
*
* @param filePath
* @param text
* @throws IOException
*/
public static void writeString2(String filePath, String text) throws IOException {
Path path = Paths.get(filePath);
// 使用newBufferedWriter创建文件并写文件
// 这里使用了try-with-resources方法来关闭流,不用手动关闭
try (BufferedWriter writer =
Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write(text);
}
}
/**
* 文件填充数据 【快速】
*
* @param filePath
* @param text
* @throws IOException
*/
public static void writeString(String filePath, String text) throws IOException {
Path path = Paths.get(filePath);
//Files.write 底层是使用Java NIO实现
Files.write(path, text.getBytes(Charset.forName("GBK")));
}
/**
* 追加数据
*
* @param filePath
* @param text
* @throws IOException
*/
public static void addToString2(String filePath, String text) throws IOException {
Path path = Paths.get(filePath);
// 使用newBufferedWriter创建文件并写文件
// 这里使用了try-with-resources方法来关闭流,不用手动关闭
try (BufferedWriter writer =
Files.newBufferedWriter(path,
StandardCharsets.UTF_8,
StandardOpenOption.APPEND)) {
writer.write(text);
}
}
/**
* 追加数据 【快速】
*
* @param filePath
* @param text
* @throws IOException
*/
public static void addToString(String filePath, String text) throws IOException {
Path path = Paths.get(filePath);
//Files.write 底层是使用Java NIO实现
Files.write(path, text.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.APPEND);
}
/**
* 生成zip压缩文件
*
* @param fileList 要压缩的文件列表
* @param zipName 生成的zip文件名
*/
public static void genZip(List<File> fileList, String zipName) {
if (fileList == null) {
return;
}
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (File file : fileList) {
log.info("genZip:{}", file.getPath());
try {
zos.putNextEntry(new ZipEntry(file.getName()));
int len;
// 定义缓冲区
byte[] buf = new byte[1024];
FileInputStream fis = new FileInputStream(file);
while ((len = fis.read(buf)) != -1) {
zos.write(buf, 0, len);
}
fis.close();
zos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 压缩成ZIP 方法1
*
* @param srcDir 压缩文件夹路径
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String srcDir, String zipName, boolean KeepDirStructure)
throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipName));
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 压缩成ZIP 方法2
*
* @param srcFiles 需要压缩的文件列表
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<String> srcFiles, String zipName, boolean KeepDirStructure) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipName));
for (String filePath : srcFiles) {
File srcFile = new File(filePath);
compress(srcFile, zos, srcFile.getName(), KeepDirStructure);
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
*
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if (KeepDirStructure) {
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
} else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
/**
* @Description: 判断路径下有没有文件
* @Param: [path]
*/
public static boolean readFolderHaveFiles(String path) {
Boolean readFolderHaveFiles=false;
File file = new File(path);
if (file.isDirectory()) {
File[] files = file.listFiles();
if (Objects.isNull(files)) {
return false;
}
} else {
return false;
}
}
/***
* checkEmptyDirectory
* 检查目录下面有没有空文件夹
* @param path path
* @return boolean
*/
public static List<String> checkEmptyDirectory(String path,List<String> paths) {
File file = new File(path);
if (file.exists()&&file.isDirectory()) {
File[] files = file.listFiles();
if (null == files || files.length == 0) {
paths.add(path);
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
checkEmptyDirectory(file2.getAbsolutePath(),paths);
} else {
continue;
}
}
}
}
return paths;
}
public static void removeEmptyDir(String path) {
File file = new File(path);
if (file.exists()&&file.isDirectory()) {
File[] files = file.listFiles();
if (null == files || files.length == 0) {
file.delete();
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
removeEmptyDir(file2.getAbsolutePath());
} else {
continue;
}
}
}
}
}
}
总结
以上就是今天要输出的内容,本文主要介绍了常用的文件操作的工具类,欢迎补充指正