一、依赖
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.9</version>
</dependency>
二、工具类代码
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipOutputStream;
public class FolderAndFileUtils {
private static Logger logger = LoggerFactory.getLogger(FolderAndFileUtils.class);
private static String SPACE = " ";
public static void copyFolder(String fromPath,String toPath) throws Exception {
File sourceFile = new File(fromPath);
File targetFile = new File(toPath);
if(!sourceFile.exists()){
logger.error("源文件夹不存在");
throw new Exception("源文件夹不存在");
}
if(!sourceFile.isDirectory()){
logger.error("源文件夹不是目录");
throw new Exception("源文件夹不是目录");
}
if(!targetFile.exists()){
targetFile.mkdirs();
}
if(!targetFile.isDirectory()){
logger.error("目标文件夹不是目录");
throw new Exception("目标文件夹不是目录");
}
File[] files = sourceFile.listFiles();
if(files == null || files.length == 0){
return;
}
for(File file : files){
String movePath = targetFile + File.separator + file.getName();
if(file.isDirectory()){
copyFolder(file.getAbsolutePath(),movePath);
}else {
copy(file.getAbsolutePath(),movePath);
}
}
}
public static void outPutJsonDataToPath(String jsonStr,String dir,String fileName,String var) throws Exception {
String path = dir + fileName;
File file = new File(path);
try {
if (file.exists()) {
file.delete();
} else {
file.createNewFile();
}
String content = formatJson(jsonStr);
Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
write.write(var);
write.write(content);
write.flush();
write.close();
logger.info(fileName + " 保存到 " + dir + " 成功");
} catch (Exception e) {
logger.error(fileName + " 保存到 " + dir + " 失败");
throw new Exception("文件保存到指定位置异常");
}
}
public static void createFolder(String path) {
File dir = new File(path);
if(!dir.exists()){
dir.mkdir();
}
}
public static void compressToZip(String fromPath, String toPath) {
File sourceFile = new File(fromPath);
File zipPath = new File(toPath);
if (!zipPath.exists()) {
zipPath.mkdirs();
}
String zipName = sourceFile.getName() + ".zip";
File zipFile = new File(zipPath + File.separator + zipName);
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFile));
writeZip(sourceFile, "", zos);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e.getCause());
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void unZip(String fileName, String destDirPath) {
long start = System.currentTimeMillis();
File srcFile = new File(destDirPath + fileName);
if (!srcFile.exists()) {
throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
}
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile, String.valueOf(Charset.forName("GBK")));
Enumeration<?> entries = zipFile.getEntries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
System.out.println("解压" + entry.getName());
if (entry.isDirectory()) {
String dirPath = destDirPath + "/" + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
} else {
File targetFile = new File(destDirPath + "/" + entry.getName());
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.close();
is.close();
}
}
long end = System.currentTimeMillis();
System.out.println("解压完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtils", e);
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void downloadImg(String downloadUrl, String filePath, String filename) {
URL url = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
url = new URL(downloadUrl);
URLConnection con = url.openConnection();
con.setConnectTimeout(5 * 1000);
inputStream = con.getInputStream();
byte[] bytes = new byte[1024];
int length;
File file = new File(filePath);
if (!file.exists()) {
boolean mkdir = file.mkdirs();
if (!mkdir) {
return;
}
}
outputStream = new FileOutputStream(file.getPath() + "\\" + filename);
while ((length = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static String formatJson(String json) {
StringBuffer result = new StringBuffer();
int length = json.length();
int number = 0;
char key = 0;
for (int i = 0; i < length; i++) {
key = json.charAt(i);
if ((key == '[') || (key == '{')) {
if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
result.append('\n');
result.append(indent(number));
}
result.append(key);
result.append('\n');
number++;
result.append(indent(number));
continue;
}
if ((key == ']') || (key == '}')) {
result.append('\n');
number--;
result.append(indent(number));
result.append(key);
if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
result.append('\n');
}
continue;
}
if ((key == ',')) {
result.append(key);
result.append('\n');
result.append(indent(number));
continue;
}
result.append(key);
}
return result.toString();
}
private static String indent(int number) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < number; i++) {
result.append(SPACE);
}
return result.toString();
}
private static void copy(String fromPath,String toPath) {
BufferedInputStream dis = null;
BufferedOutputStream dos = null;
try {
FileInputStream fis = new FileInputStream(fromPath);
FileOutputStream fos = new FileOutputStream(toPath);
dis = new BufferedInputStream(fis);
dos = new BufferedOutputStream(fos);
byte[] b = new byte[1024];
int len = 0;
while((len = dis.read(b)) != -1){
dos.write(b, 0, len);
dos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(dos != null){
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(dis != null){
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
if (file.isDirectory()) {
parentPath += file.getName() + File.separator;
File[] files = file.listFiles();
for (File f : files) {
writeZip(f, parentPath, zos);
}
} else {
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry zipEntry = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(zipEntry);
zos.setEncoding("GBK");
int len;
byte[] buffer = new byte[1024 * 10];
while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
zos.write(buffer, 0, len);
zos.flush();
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e.getCause());
} finally {
try {
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static boolean deleteDir(File dir){
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}