标题
最新工作涉及到文件操作的内容,顺带花点时间把各种业务场景的方法都总结出来,供大家参考
对应Maven依赖、这块提醒千万别倒错包,这块的方法本人都亲测过,如果报错看下依赖是否正确
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.5</version>
</dependency>
使用方法前建议看方法的注释及代码,是否满足自己的实际需求,必要时调整一下即可
package cn.kgc.itrip.search.test;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class FileUtil {
private static void createMoreFiles(String path) throws IOException {
Files.createDirectories(Paths.get(path));
Files.write(Paths.get(path + "test2.log"), "helloTest2".getBytes());
Files.write(Paths.get(path + "test3\\test3.log"), "helloTest3".getBytes());
}
public static boolean isDirectoryOrFile(String path) {
File file = new File(path);
if (file.isDirectory()) {
return true;
}
if (file.isFile()) {
return false;
}
return false;
}
public static boolean checkFileExist(String filePath) {
File file = new File(filePath);
return file.exists() ? true : false;
}
public static boolean checkDirectoryExist(String directoryPath) {
File file = new File(directoryPath);
if (!file.exists() && !file.isDirectory()) {
return false;
}
return true;
}
public static boolean isHaveAnyFile(String filepath) throws FileNotFoundException, IOException {
File file = new File(filepath);
if (!file.isDirectory()) {
System.out.println("请输入一个目录");
return false;
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
if (filelist[i].contains(".")) {
System.out.println("该目录下存在文件");
return true;
}
}
System.out.println("该目录下不存在文件");
return false;
}
return false;
}
public static List<String> getFileName(String filepath, String fileType) throws FileNotFoundException, IOException {
String type = ".";
if (!("".equals(fileType) || null == fileType)) {
type = "." + fileType;
}
File file = new File(filepath);
List<String> listFileName = new ArrayList();
if (!file.isDirectory()) {
System.out.println("请输入一个目录");
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
if (filelist[i].contains(type)) {
listFileName.add(filelist[i]);
}
}
}
return listFileName;
}
public static ArrayList<File> getFilesAll(String path) {
ArrayList<File> files = new ArrayList<File>();
File file = new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
files.add(tempList[i]);
}
if (tempList[i].isDirectory()) {
ArrayList<File> files1 = getFilesAll(tempList[i].getPath());
files.addAll(files1);
}
}
return files;
}
public static ArrayList<File> getFilesList(String path, boolean childFolder) {
ArrayList<File> files = new ArrayList<File>();
File file = new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
files.add(tempList[i]);
}
if (tempList[i].isDirectory() && childFolder) {
ArrayList<File> files1 = getFilesList(tempList[i].getPath(), childFolder);
files.addAll(files1);
}
}
return files;
}
public static ArrayList<File> getDirList(String path, boolean childFolder) {
ArrayList<File> files = new ArrayList<File>();
File file = new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isDirectory()) {
files.add(tempList[i]);
}
if (tempList[i].isDirectory() && childFolder) {
ArrayList<File> files1 = getDirList(tempList[i].getPath(), childFolder);
files.addAll(files1);
}
}
return files;
}
public static int repetitionNum(String dirPath, String name, boolean falgFile, boolean childFolder) {
ArrayList<File> filesDir = new ArrayList<>();
int count = 0;
if (falgFile) {
filesDir = getFilesList(dirPath, childFolder);
} else {
filesDir = getDirList(dirPath, childFolder);
}
for (File file : filesDir) {
if (name.equals(file.getName())) {
count++;
}
}
return count;
}
public static boolean createDirectory(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
flag = file.mkdirs();
} else {
}
return flag;
}
public static boolean createDirectory1(String path) {
boolean flag = false;
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
} else {
}
return flag;
}
public static boolean createDirectoryFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
try {
flag = file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
return flag;
}
public static void createNewFile(String filePath) {
File file = new File(filePath);
if (file.exists()) {
file.delete();
} else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void copyFileToWriteFile(String sourceFilePath, String targetFilePath) {
Writer writer = null;
InputStream ins = null;
createDirectory1(targetFilePath);
try {
writer = new FileWriter(targetFilePath);
ins = new FileInputStream(new File(sourceFilePath));
IOUtils.copy(ins, writer);
ins.close();
} catch (IOException e) {
System.out.println("复制文件时出错,请检查!" + e);
} finally {
ins = null;
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(ins);
}
}
public static boolean copyFile(String sourceFile, String targetFile) {
File srcfile = new File(sourceFile);
File destfile = new File(targetFile);
try {
FileUtils.copyFile(srcfile, destfile);
} catch (IOException e) {
System.out.println("复制文件[" + sourceFile + "]到指定位置[" + targetFile + "]时出错,请检查!");
return false;
} finally {
if (null != srcfile) {
srcfile = null;
}
if (null != destfile) {
destfile = null;
}
}
return true;
}
public static void copyFileToDirectory(String file, String directory) {
File srcfile = new File(file);
File destDir = new File(directory);
try {
org.apache.commons.io.FileUtils.copyFileToDirectory(srcfile, destDir);
} catch (IOException e) {
} finally {
srcfile = null;
destDir = null;
}
}
public static void copyFilesCope(String srcPath, String targetPath) {
File src = new File(srcPath);
File desc = new File(targetPath);
if (!desc.exists()) {
desc.mkdirs();
}
long start = System.currentTimeMillis();
try {
copyFilesCope(src, desc);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void copyFilesCope(File src, File desc) throws IOException {
if (src.isFile()) {
FileInputStream fis = new FileInputStream(src);
String path = desc.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] b = new byte[1024 * 1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bos.flush();
bos.close();
bis.close();
} else {
File[] files = src.listFiles();
if (files.length == 0) {
String srcPath = src.getName();
String descPath = (desc.getAbsolutePath().endsWith("\\") ? desc.getAbsolutePath() : desc.getAbsolutePath() + "\\" + srcPath);
File newFile = new File(descPath);
if (!newFile.exists()) {
newFile.mkdirs();
}
} else {
for (File f : files) {
String srcPath = f.getName();
String descPath = "";
if (f.isFile()) {
descPath = desc.getAbsolutePath() + "\\" + f.getName();
}
if (f.isDirectory()) {
descPath = (desc.getAbsolutePath().endsWith("\\") ? desc.getAbsolutePath() : desc.getAbsolutePath() + "\\" + srcPath);
}
File newFile = new File(descPath);
if (f.isDirectory()) {
if (!newFile.exists()) {
newFile.mkdirs();
}
}
copyFilesCope(f, newFile);
}
}
}
}
public static void copyFileByName(String oldFilePath, String targetPath) throws IOException {
File file = new File(oldFilePath);
File file2 = new File(targetPath);
if (!file2.exists()) {
file2.mkdirs();
}
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
String name = oldFilePath.substring(oldFilePath.lastIndexOf("\\") + 1, oldFilePath.length());
FileOutputStream fos = new FileOutputStream(targetPath + File.separator + name);
byte[] b = new byte[fis.available()];
int len = 0;
while ((len = fis.read(b)) != -1) {
fos.write(b, 0, len);
fos.flush();
}
fos.close();
fis.close();
}
}
public static void copyFileByType(String oldPath, String newPath, String fileType) {
File files = new File(oldPath);
File file2 = new File(newPath);
if (!file2.exists()) {
file2.mkdirs();
}
getAllFile(files, newPath, fileType);
}
public static void getAllFile(File file, String newPath, String fileType) {
File[] files = file.listFiles();
for (File fileName : files) {
if (fileName.isDirectory()) {
} else {
String name = fileName.getAbsolutePath();
if (name.endsWith("." + fileType)) {
fileCopy(name, newPath);
}
}
}
}
public static void fileCopy(String str, String newPath) {
String substring = str.trim().substring(str.lastIndexOf("\\") + 1);
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(str);
fw = new FileWriter(newPath + File.separator + substring);
int len = 0;
char[] ch = new char[1024];
while ((len = fr.read(ch)) != -1) {
fw.write(ch, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null && fr != null) {
try {
fw.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
FileUtil.copyFileToDirectory(
"C:\\Users\\雷神\\Desktop\\ribao\\h1h\\a.txt",
"C:\\Users\\雷神\\Desktop\\ribao\\h2h\\cc");
}
public static void stringToFile(String str, String targetFilePath, String encode) {
String strWrite = str;
try {
IOUtils.write(strWrite, new FileOutputStream(targetFilePath), encode);
} catch (IOException e) {
} finally {
strWrite = null;
}
}
public static void stringToFile(String str, String targetFilePath) {
stringToFile(str, targetFilePath, "UTF-8");
}
public static String urlToString(String urlPath, String encode) {
String str = "";
InputStream ins = null;
try {
URL url = new URL(urlPath);
ins = url.openStream();
str = IOUtils.toString(ins, encode);
ins.close();
} catch (MalformedURLException e) {
System.out.println("URL地址格式错误,请检查!");
} catch (IOException e) {
System.out.println("文件流出错,请检查!");
} finally {
ins = null;
IOUtils.closeQuietly(ins);
}
return str;
}
public static String urlToString(String urlPath) {
return urlToString(urlPath, "UTF-8");
}
public static void urlToFile(String urlPath, String targetFilePath, String encode) {
stringToFile(urlToString(urlPath, encode), targetFilePath, encode);
}
public static void urlToFile(String urlPath, String targetFilePath) {
stringToFile(urlToString(urlPath), targetFilePath);
}
public static void delDirectoryFiles(String directory) {
File dir = new File(directory);
try {
org.apache.commons.io.FileUtils.cleanDirectory(dir);
} catch (IOException e) {
e.printStackTrace();
} finally {
dir = null;
}
}
public static void delDirectoryAndFiles(String directory) {
File dir = new File(directory);
try {
org.apache.commons.io.FileUtils.deleteDirectory(dir);
} catch (IOException e) {
} finally {
dir = null;
}
}
public static Long getDirectorySize(String directory) {
File file = new File(directory);
long size = FileUtils.sizeOfDirectory(file);
return size;
}
public static void createDirectoryOrUpdateModifyDateTime(String path) {
File file = new File(path);
try {
FileUtils.touch(file);
} catch (IOException e) {
} finally {
file = null;
}
}
public static String fileToString(String file, String encode) {
String str = "";
InputStream ins = null;
try {
ins = new FileInputStream(file);
str = IOUtils.toString(ins, encode);
ins.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
ins = null;
IOUtils.closeQuietly(ins);
}
return str;
}
public static String fileToString(String file) {
return fileToString(file, "UTF-8");
}
public static String fileToStringWithOutIOUtils(String fielPath, String encode) {
StringBuffer sb = null;
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader in = null;
try {
fis = new FileInputStream(fielPath);
isr = new InputStreamReader(fis, encode);
in = new BufferedReader(isr);
String s = new String();
sb = new StringBuffer();
while ((s = in.readLine()) != null) {
sb.append(s + "\n");
}
in.close();
isr.close();
fis.close();
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
} finally {
in = null;
isr = null;
fis = null;
}
return sb.toString();
}
public static String fileToStringWithOutIOUtils(String fielPath) {
return fileToStringWithOutIOUtils(fielPath, "UTF-8");
}
public static Integer inputStreamToFile(InputStream is, String filePath) {
Integer result = 0;
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
result = 1;
} catch (FileNotFoundException e) {
result = 0;
} catch (IOException e) {
result = 0;
} finally {
try {
is.close();
out.close();
} catch (IOException e) {
result = 0;
}
}
return result;
}
@SuppressWarnings("deprecation")
public static Integer readerToFile(Reader reader, String filePath, String encode) {
Integer result = 0;
try {
stringToFile(IOUtils.toString(IOUtils.toByteArray(reader, encode)), filePath);
result = 1;
} catch (IOException e) {
result = 0;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return result;
}
public static byte[] getBytesFromFile(File f) throws Exception {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(f);
byte[] b = new byte[fileInputStream.available()];
fileInputStream.read(b);
return b;
} catch (Exception e) {
throw e;
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
}
}
}
public static void wirteDataToFile(String savePath, byte[] data) throws Exception {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(savePath);
fileOutputStream.write(data);
fileOutputStream.flush();
} catch (Exception e) {
throw e;
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
}
}
}
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);
delFolder(path + "/" + tempList[i]);
flag = true;
}
}
return flag;
}
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath);
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
myFilePath.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void removeDirectory(File file) {
File[] files = file.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
files[i].delete();
} else if (files[i].isDirectory()) {
removeDirectory(files[i]);
}
files[i].delete();
}
}
}
public static void removeDirectoryAll(File file) {
removeDirectory(file);
file.deleteOnExit();
}
public static boolean deleteFile(String sPath) {
boolean flag;
flag = false;
File file = new File(sPath);
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
public static boolean deleteFileList(String sPath, List<String> fileNames) {
boolean flag;
flag = false;
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
if (!isDirectoryOrFile(sPath)) {
return false;
}
for (String fileName : fileNames) {
File file = new File(sPath + fileName);
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
}
return flag;
}
public static boolean deleteDirectoryAll(String sPath) {
boolean flag = false;
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
flag = true;
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag) {
break;
}
}
else {
flag = deleteDirectoryAll(files[i].getAbsolutePath());
if (!flag) {
break;
}
}
}
if (!flag) {
return false;
}
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
private static void circleMethod(String dirPath, String fileName) {
File file = new File(dirPath);
if (file.isDirectory()) {
String[] dirPathList = file.list();
for (int i = 0; i < dirPathList.length; i++) {
String filePath = dirPath + File.separator + dirPathList[i];
File fileDelete = new File(filePath);
if (fileDelete.getName().equals(fileName)) {
fileDelete.delete();
}
}
}
}
public static void delMethod(String filePath, String fileNames) {
String[] name = fileNames.split(",");
for (String fileName : name) {
File file = new File(filePath + "\\" + fileName);
if (file.exists() && file.isFile()) {
file.delete();
}
}
}
public static void reNameFile(String oldFilePath, String newFilePath) {
File oldName = new File(oldFilePath);
File newName = new File(newFilePath);
oldName.renameTo(newName);
}
private static void circleMethodType(String dirPath, String fileType) {
File file = new File(dirPath);
if (file.isDirectory()) {
String[] dirPathList = file.list();
for (int i = 0; i < dirPathList.length; i++) {
String filePath = dirPath + File.separator + dirPathList[i];
File fileDelete = new File(filePath);
if (fileDelete.getName().contains("." + fileType)) {
fileDelete.delete();
}
}
}
}
public static boolean duplicateName(List<File> list, String targetFilePath) {
File targetFile = new File(targetFilePath);
for (File file : list) {
if (file.getName().equals(targetFile.getName())) {
return true;
}
}
return false;
}
public static boolean duplicateName(List<File> list, File targetFilePath) {
for (File file : list) {
if (file.getName().equals(targetFilePath.getName())) {
return true;
}
}
return false;
}
public static String getNewName(String oldAbsolutePath, int no) {
File file = new File(oldAbsolutePath);
if (file.isFile()) {
String name = file.getName();
String type = "." + getFileNameOrType(name, "2");
name = getFileNameOrType(name, "1");
name = name + "(" + (no) + ")";
return name + type;
}
if (file.isDirectory()) {
String name = file.getName();
name = name + "(" + (no) + ")";
return name;
}
return null;
}
public static void reNameDirectory(String oldDir, String newDir) {
File folder = new File(oldDir);
File newfolder = new File(newDir);
folder.renameTo(newfolder);
}
public static void modifyFileNames(String filePath) {
File file = new File(filePath);
File[] list = file.listFiles();
if (file.exists() && file.isDirectory()) {
for (int i = 0; i < list.length; i++) {
if (!list[i].getName().contains(".")) {
continue;
}
String name = list[i].getName();
int index = name.indexOf(0);
String newName = "abc";
String name2 = newName + name.substring(index + 1);
File dest = new File(filePath + File.separator + name2);
list[i].renameTo(dest);
}
}
}
public static void recursiveTraversalFolder(String path) {
File folder = new File(path);
if (folder.exists()) {
File[] fileArr = folder.listFiles();
if (null == fileArr || fileArr.length == 0) {
System.out.println("文件夹是空的!");
return;
} else {
File newDir = null;
String newName = "";
String fileName = null;
File parentPath = new File("");
for (File file : fileArr) {
if (file.isDirectory()) {
System.out.println("文件夹:" + file.getAbsolutePath() + ",继续递归!");
recursiveTraversalFolder(file.getAbsolutePath());
} else {
fileName = file.getName();
parentPath = file.getParentFile();
if (fileName.contains("abc")) {
newName = fileName.replaceAll("abc", "gg");
newDir = new File(parentPath + "/" + newName);
file.renameTo(newDir);
System.out.println("修改后:" + newDir);
}
}
}
}
} else {
System.out.println("文件不存在!");
}
}
public static String getFileNameOrType(String fileName,String flag){
if ("1".equals(flag)){
return fileName.substring(0,fileName.lastIndexOf("."));
}
return fileName.substring(fileName.lastIndexOf(".")+1);
}
public static int getLastIndexOfGang(String filePath){
return filePath.lastIndexOf(File.separator);
}
public static String getParentPath(String path) {
File file = new File(path);
File parentFile = file.getParentFile();
return parentFile.getAbsolutePath();
}
public static String getNeedPath(String sPath){
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
return sPath;
}
public static boolean createDirectoryOrFile(String path,boolean directoryPath , boolean createFile) {
File file = new File(path);
if (directoryPath) {
if (! file.exists()) {
return file.mkdirs();
}
}else {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (createFile) {
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public static String linuxPath(String path) {
String p = StringUtils.replace(path, "\\", "/");
p = StringUtils.join(StringUtils.split(p, "/"), "/");
if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")) {
p += "/";
}
if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")) {
p = p + "/";
}
return p;
}
压缩这块分好几种情况 涉及内容较多单独拿到这块
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public static boolean fileDirectoryToZip(String srcDir, String outZipDir, boolean KeepDirStructure) {
if (KeepDirStructure){
System.out.println("请确认压缩文件夹下子文件夹不存在同名文件(即所有文件名唯一),否则会压缩失败,\n" +
"建议设置为false,保留原文件目录格式");
}
File file = new File(srcDir);
if (!file.isDirectory()) {
return false;
}
File lastZipFile = new File(outZipDir);
File parentFile = lastZipFile.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
FileOutputStream fos2 = null;
try {
fos2 = new FileOutputStream(lastZipFile);
System.out.println(srcDir + "目录压缩到: " + outZipDir);
toZip(srcDir, fos2, KeepDirStructure);
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
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();
}
}
}
}
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception {
byte[] buf = new byte[2 * 1024];
if (sourceFile.isFile()) {
zos.putNextEntry(new ZipEntry(name));
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
if (KeepDirStructure) {
zos.putNextEntry(new ZipEntry(name + "/"));
zos.closeEntry();
}
} else {
for (File file : listFiles) {
if (KeepDirStructure) {
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
上面仅仅针对文件夹操作 ,这个能针对单个文件或文件进行压缩
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public static boolean toZip1(String source, String destination) {
try {
FileOutputStream out = new FileOutputStream(destination);
ZipOutputStream zipOutputStream = new ZipOutputStream(out);
File sourceFile = new File(source);
compress1(sourceFile, zipOutputStream, sourceFile.getName());
zipOutputStream.flush();
zipOutputStream.close();
} catch (IOException e) {
System.out.println("failed to zip compress, exception");
return false;
}
return true;
}
private static void compress1(File sourceFile, ZipOutputStream zos, String name) throws IOException {
byte[] buf = new byte[1024];
if (sourceFile.isFile()) {
zos.putNextEntry(new ZipEntry(name));
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
zos.putNextEntry(new ZipEntry(name + "/"));
zos.closeEntry();
} else {
for (File file : listFiles) {
compress1(file, zos, name + "/" + file.getName());
}
}
}
}
上面都是单压缩 下面说说多压缩
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public static boolean zipFiles(String[] srcFilePathArray, String zipFilePath) {
File[] srcfile = new File[srcFilePathArray.length];
for (int i = 0; i < srcfile.length; i++) {
srcfile[i] = new File(srcFilePathArray[i]);
}
File zipFile = new File(zipFilePath);
return zipFiles(srcfile, zipFile);
}
public static boolean zipFiles(File[] srcfile, File zipfile) {
boolean reFlag = false;
byte[] buf = new byte[10240];
ZipOutputStream out = null;
FileInputStream in = null;
try {
out = new ZipOutputStream(new FileOutputStream(zipfile));
out.setEncoding("UTF-8");
for (int i = 0; i < srcfile.length; i++) {
in = new FileInputStream(srcfile[i]);
out.putNextEntry(new ZipEntry(srcfile[i].getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
in = null;
}
out.close();
out = null;
reFlag = true;
System.out.println("压缩完成,文件详细信息为:" + zipfile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return reFlag;
}
压缩指定文件夹后生成压缩文件(zip、rar 格式):generateFile
public static void generateFile(String path, String tarPath) throws Exception {
File file = new File(path);
if (!file.exists()) {
throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");
}
String generateFile = tarPath;
File compress = new File(generateFile);
if (!compress.getParentFile().exists()) {
compress.getParentFile().mkdirs();
}
String generateFileName = compress.getAbsolutePath();
FileOutputStream outputStream = new FileOutputStream(generateFileName);
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
generateFile(zipOutputStream, file, "");
System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);
zipOutputStream.close();
}
private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {
if (file.isDirectory()) {
File[] files = file.listFiles();
out.putNextEntry(new ZipEntry(dir + "/"));
dir = dir.length() == 0 ? "" : dir + "/";
for (int i = 0; i < files.length; i++) {
generateFile(out, files[i], dir + files[i].getName());
}
} else {
FileInputStream inputStream = new FileInputStream(file);
out.putNextEntry(new ZipEntry(dir));
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
inputStream.close();
}
}
解压缩 可以解压zip、rar 压缩文件到指定文件夹下:decompress
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public static void decompress(File srcFile, String destPath) throws Exception {
decompress(srcFile, new File(destPath));
}
public static void decompress(File srcFile, File destFile) throws Exception {
CheckedInputStream cis = new CheckedInputStream(new FileInputStream(srcFile), new CRC32());
ZipInputStream zis = new ZipInputStream(cis, Charset.forName("GBK"));
decompress(destFile, zis);
zis.close();
}
public static void decompress(String srcPath, String destPath) throws Exception {
File srcFile = new File(srcPath);
decompress(srcFile, destPath);
}
private static void decompress(File destFile, ZipInputStream zis) throws Exception {
ZipEntry entry = null;
while ((entry = zis.getNextEntry()) != null) {
String dir = destFile.getPath() + File.separator + entry.getName();
File dirFile = new File(dir);
fileProber(dirFile);
if (entry.isDirectory()) {
dirFile.mkdirs();
} else {
decompressFile(dirFile, zis);
}
zis.closeEntry();
}
}
private static void fileProber(File dirFile) {
File parentFile = dirFile.getParentFile();
if (!parentFile.exists()) {
fileProber(parentFile);
parentFile.mkdir();
}
}
private static void decompressFile(File destFile, ZipInputStream zis) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
int count;
byte data[] = new byte[1024];
while ((count = zis.read(data, 0, 1024)) != -1) {
bos.write(data, 0, count);
}
bos.close();
}
这个比上面精简,可能是导入依赖的原因,上面用的是jdk自带的, 两者功能一样但是个人推荐使用这个
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
public static void releaseZipToFile(String sourceZip, String outFileName)
throws IOException {
ZipFile zfile = new ZipFile(sourceZip);
Enumeration<?> zList = zfile.getEntries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
continue;
}
OutputStream os = new BufferedOutputStream(new FileOutputStream(
getRealFileName(outFileName, ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
System.out.println("Extracted: " + ze.getName());
}
zfile.close();
}
public static File getRealFileName(String baseDir, String absFileName) {
String[] dirs = absFileName.split("/");
File ret = new File(baseDir);
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {
ret.mkdirs();
}
ret = new File(ret, dirs[dirs.length - 1]);
return ret;
}
这个方法在支持保存原有路径的基础上实现了不保留目录结构时重命名同名文件
import java.io.*;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
private static HashMap<Object, Object> index = new HashMap<>();
private static int count = 0;
public static File zip(String compressedFileName, String filePath, boolean keepStructure) throws IOException {
return zip(compressedFileName, new File(filePath), keepStructure);
}
public static File zip(String compressedFileName, File file, boolean keepStructure) throws IOException {
if (file == null || !file.exists()) {
return null;
}
if (keepStructure) {
count = 0;
index = new HashMap<>(10);
}
File zipFile = new File(compressedFileName);
if (!zipFile.getParentFile().exists()) {
zipFile.getParentFile().mkdirs();
}
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
if (!file.isDirectory()) {
addCompressedFile(zipOut, null, file);
} else {
addCompressedFloder(zipOut, null, file, keepStructure);
}
zipOut.close();
System.out.println("压缩完成");
return zipFile;
}
private static void addCompressedFloder(ZipOutputStream zipOut, String parentPath, File file, boolean keepStructure) throws IOException {
if (file == null || !file.exists()) {
return;
}
parentPath = empty(parentPath);
if (!file.isDirectory()) {
if (keepStructure) {
addCompressedFile(zipOut, parentPath, file);
} else {
addCompressedFile(zipOut, null, file);
}
} else {
File[] files = file.listFiles();
assert files != null;
if (keepStructure) {
zipOut.putNextEntry(new ZipEntry(parentPath + file.getName() + File.separator));
}
for (File openFile : files) {
addCompressedFloder(zipOut, parentPath + file.getName() + File.separator, openFile, keepStructure);
}
}
}
private static void addCompressedFile(ZipOutputStream zipOut, String parentPath, File file) throws IOException {
InputStream input = new FileInputStream(file);
String fileName = file.getName();
if (parentPath != null) {
zipOut.putNextEntry(new ZipEntry(parentPath + fileName));
} else {
if (index.containsKey(fileName)) {
String endType = "";
String prefixName = "";
if (fileName.contains(".")) {
endType = fileName.substring(fileName.lastIndexOf("."));
prefixName = fileName.substring(0, fileName.lastIndexOf("."));
count++;
zipOut.putNextEntry(new ZipEntry(prefixName + "(" + count + ")" + endType));
index.put(prefixName + "(" + count + ")" + endType, true);
} else {
count++;
zipOut.putNextEntry(new ZipEntry("(" + count + ")" + fileName));
index.put("(" + count + ")" + fileName, true);
}
} else {
zipOut.putNextEntry(new ZipEntry(fileName));
index.put(fileName, true);
}
}
int temp;
while ((temp = input.read()) != -1) {
zipOut.write(temp);
}
zipOut.closeEntry();
input.close();
}
private static String empty(String s) {
if (isEmpty(s)) {
return "";
}
return s;
}
private static boolean isEmpty(String str) {
return str == null || "".equals(str.trim());
}
}
实现复制多个文件(夹)到指定目录下如果重名则重命名:copyFileOrDir 即可实现把不同路径下的文件或目录压缩到同一个文件夹下
import org.apache.commons.io.FileUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileUtil {
public static void main(String[] args) {
List<File> fileList = new ArrayList<>();
fileList.add(new File("C:\\Users\\Desktop\\ribao\\h2h"));
fileList.add(new File("C:\\Users\\Desktop\\ribao\\h2\\h2h"));
fileList.add(new File("C:\\Users\\Desktop\\ribao\\rr"));
fileList.add(new File("C:\\Users\\Desktop\\ribao\\test2\\rr"));
fileList.add(new File("C:\\Users\\Desktop\\ribao\\h2h\\b.txt"));
fileList.add(new File("C:\\Users\\Desktop\\ribao\\h2h\\c.txt"));
fileList.add(new File("C:\\Users\\Desktop\\ribao\\h2\\h2h\\b.txt"));
copyFileOrDir(fileList, "C:\\Users\\Desktop\\ribao\\target");
}
public static void copyFileOrDir(List<File> srcFiles, String targetAbsolutePath) {
int i = 0;
for (File srcFile : srcFiles) {
++i;
ArrayList<File> filesAll = getDirAllFile(targetAbsolutePath, false);
if (null == filesAll || filesAll.size() <= 0) {
if (srcFile.isFile()) {
String dirPath = targetAbsolutePath.endsWith(File.separator) ? targetAbsolutePath : targetAbsolutePath + File.separator;
copyFile(srcFile.getAbsolutePath(), dirPath + srcFile.getName());
} else {
String dirPath = targetAbsolutePath.endsWith(File.separator) ? targetAbsolutePath : targetAbsolutePath + File.separator;
copyFilesCope(srcFile.getAbsolutePath(), dirPath + srcFile.getName());
}
} else {
if (duplicateName(filesAll, srcFile)) {
if (srcFile.isFile()) {
String newFileName = getNewName(srcFile.getAbsolutePath(), i);
String filePath = targetAbsolutePath.endsWith(File.separator) ? targetAbsolutePath : targetAbsolutePath + File.separator;
copyFile(srcFile.getAbsolutePath(), filePath + newFileName);
} else {
String newDirName = getNewName(srcFile.getAbsolutePath(), i);
String dirPath = targetAbsolutePath.endsWith(File.separator) ? targetAbsolutePath : targetAbsolutePath + File.separator;
copyFilesCope(srcFile.getAbsolutePath(), dirPath + newDirName);
}
} else {
if (srcFile.isFile()) {
String filePath = targetAbsolutePath.endsWith(File.separator) ? targetAbsolutePath : targetAbsolutePath + File.separator;
copyFile(srcFile.getAbsolutePath(), filePath + srcFile.getName());
} else {
String dirPath = targetAbsolutePath.endsWith(File.separator) ? targetAbsolutePath : targetAbsolutePath + File.separator;
copyFilesCope(srcFile.getAbsolutePath(), dirPath + srcFile.getName());
}
}
}
}
}
public static String getNewName(String oldAbsolutePath, int no) {
File file = new File(oldAbsolutePath);
if (file.isFile()) {
String name = file.getName();
String type = "." + getFileNameOrType(name, "2");
name = getFileNameOrType(name, "1");
name = name + "(" + (no) + ")";
return name + type;
}
if (file.isDirectory()) {
String name = file.getName();
name = name + "(" + (no) + ")";
return name;
}
return null;
}
public static String getFileNameOrType(String fileName, String flag) {
if ("1".equals(flag)) {
return fileName.substring(0, fileName.lastIndexOf("."));
}
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
public static boolean duplicateName(List<File> list, String targetFilePath) {
File targetFile = new File(targetFilePath);
for (File file : list) {
if (file.getName().equals(targetFile.getName())) {
return true;
}
}
return false;
}
public static boolean duplicateName(List<File> list, File targetFilePath) {
for (File file : list) {
if (file.getName().equals(targetFilePath.getName())) {
return true;
}
}
return false;
}
public static ArrayList<File> getDirAllFile(String path, boolean childrenDir) {
ArrayList<File> files = new ArrayList<File>();
File file = new File(path);
File[] tempList = file.listFiles();
if (null == tempList || tempList.length == 0) {
return null;
}
for (int i = 0; i < tempList.length; i++) {
files.add(tempList[i]);
if (childrenDir) {
if (tempList[i].isDirectory()) {
ArrayList<File> files1 = getDirAllFile(tempList[i].getPath(), childrenDir);
files.addAll(files1);
}
}
}
return files;
}
public static boolean copyFile(String sourceFile, String targetFile) {
File srcfile = new File(sourceFile);
File destfile = new File(targetFile);
try {
FileUtils.copyFile(srcfile, destfile);
} catch (IOException e) {
System.out.println("复制文件[" + sourceFile + "]到指定位置[" + targetFile + "]时出错,请检查!");
return false;
} finally {
if (null != srcfile) {
srcfile = null;
}
if (null != destfile) {
destfile = null;
}
}
return true;
}
public static void copyFilesCope(String srcPath, String targetPath) {
File src = new File(srcPath);
File desc = new File(targetPath);
if (!desc.exists()) {
desc.mkdirs();
}
long start = System.currentTimeMillis();
try {
copyFilesCope(src, desc);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void copyFilesCope(File src, File desc) throws IOException {
if (src.isFile()) {
FileInputStream fis = new FileInputStream(src);
String path = desc.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] b = new byte[1024 * 1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bos.flush();
bos.close();
bis.close();
} else {
File[] files = src.listFiles();
if (files.length == 0) {
String srcPath = src.getName();
String descPath = (desc.getAbsolutePath().endsWith("\\") ? desc.getAbsolutePath() : desc.getAbsolutePath() + "\\" + srcPath);
File newFile = new File(descPath);
if (!newFile.exists()) {
newFile.mkdirs();
}
} else {
for (File f : files) {
String srcPath = f.getName();
String descPath = "";
if (f.isFile()) {
descPath = desc.getAbsolutePath() + "\\" + f.getName();
}
if (f.isDirectory()) {
descPath = (desc.getAbsolutePath().endsWith("\\") ? desc.getAbsolutePath() : desc.getAbsolutePath() + "\\" + srcPath);
}
File newFile = new File(descPath);
if (f.isDirectory()) {
if (!newFile.exists()) {
newFile.mkdirs();
}
}
copyFilesCope(f, newFile);
}
}
}
}
}
|