Java文件压缩(删除)BufferedInputStream
public class FileUtils {
public static void main(String[] args) {
String compressPath = "D:\\20201216";
long zipBegin = System.currentTimeMillis();
fileToZip(compressPath);
long zipEnd = System.currentTimeMillis();
System.out.println("zipTime:" + (zipEnd - zipBegin));
}
/**
* 压缩文件夹或文件
*
* @param compressPath 需要压缩的文件夹目录
* @return
*/
public static boolean fileToZip(String compressPath) {
boolean flag = false;
try {
ZipOutputStream zos = null;
File file = new File(compressPath);
if (file.isDirectory()) {
zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(compressPath + ".zip")));
// 递归压缩文件夹,最后一个参数传" ",则压缩包不会有当前文件夹;传file.getName(),则有当前文件
compressZip(zos, file, file.getName());
} else {
zos = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(compressPath.substring(0, compressPath.lastIndexOf(".")) + ".zip")));
zipOFile(zos, file); // 压缩单个文件
}
zos.closeEntry();
zos.close();
flag = true;
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* @param zos
* @param file
* @param suffixPath 文件拼接的路径
*/
private static void compressZip(ZipOutputStream zos, File file, String suffixPath) {
File[] listFiles = file.listFiles();
for (File f : listFiles) {
if (f.isDirectory()) {
if (suffixPath.equals("")) {
compressZip(zos, f, f.getName());
} else {
compressZip(zos, f, suffixPath + File.separator + f.getName());
}
}else {
toZip(zos,f,suffixPath);
}
}
}
/**
* 压缩文件
*
* @param zos
* @param file
* @param suffixPath
*/
private static void toZip(ZipOutputStream zos, File file, String suffixPath) {
try {
ZipEntry zEntry = null;
if(suffixPath.equals("")) {
zEntry = new ZipEntry(file.getName());
}else {
zEntry = new ZipEntry(suffixPath + file.separator + file.getName());
System.out.println(file.getName());
}
zos.putNextEntry(zEntry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] arr = new byte[1024];
int len = 0;
while((len = bis.read(arr)) != -1) {
zos.write(arr, 0, len);
}
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 压缩单个文件
* @param zos
* @param file
*/
private static void zipOFile(ZipOutputStream zos, File file) {
try {
ZipEntry zEntry = new ZipEntry(file.getName());
zos.putNextEntry(zEntry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] arr = new byte[1024];
int len = 0;
while((len = bis.read(arr)) != -1) {
zos.write(arr, 0, len);
}
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 删除文件夹
* @param file 文件夹路径
*/
public static void deleteFile(File file) {
if(file == null || !file.exists()) {
System.out.println("文件删除失败,检查文件路径!");
return;
}
File[] files = file.listFiles();
for(File f : files) {
if(f.isDirectory()) {
deleteFile(f);
}else {
f.delete();
}
}
file.delete(); //单文件
}
}

浙公网安备 33010602011771号