1:文件壓縮、
2:遞歸壓縮文件、
3:下載單個文件、
4:刪除單個文件、
5:解壓文件到指定文件夾、
6:上傳文件、
7:讀取多級目錄下的所有文件、
8:文件複製到另一個目錄下
9:往文件裏寫內容
package com.ed.core.util;
import com.ed.core.commom.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* @ProjectName: gitIdeaWork
* @Package: com.ed.core.util
* @ClassName: ZipOpUtil
* @Author: zhao
* @Description: 資源打包下載類 https://my.oschina.net/Rayn/blog/471309
* @Date: 2020/2/21 16:50
* @Version: 1.0
*
*/
public class ZipOpUtil {
private static Logger logger = LoggerFactory.getLogger(ZipOpUtil.class);
public static void main(String[] args) {
moveTotherFolders("C:\\Users\\zhao\\Desktop\\12121\\1.txt","C:\\Users\\zhao\\Desktop\\12121\\12\\");
/*zipFile("C:\\Users\\zhao\\Desktop\\12121",new File("C:\\Users\\zhao\\Desktop\\56.tar"));
*/
try {
decompress("C:\\Users\\zhao\\Desktop\\56.tar","C:\\Users\\zhao\\Desktop\\56\\pp\\");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 將多個文件打包到一個zip中
*
* @param sourceFolder
* @param zipFile
* @return
*/
public static boolean zipFile(String sourceFolder, File zipFile) {
boolean isOk = true;
File f = new File(sourceFolder);
ZipOutputStream out = null;
try {
if (!f.exists()) {
f.mkdirs();
}
out = new ZipOutputStream(new FileOutputStream(zipFile));
zip(out, f, "");
out.flush();
// FileUtils.deleteDirectory(f);
} catch (Exception e) {
e.printStackTrace();
logger.info("壓縮文件出錯!");
} finally {
if (null != out) {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println("壓縮文件完成!!!");
return isOk;
}
/**
* 遞歸壓縮文件
*
* @param out
* @param f
* @param base
* @throws Exception
*/
private static void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
logger.info(base);
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
/**
* 下載單個文件
*
* @param file
* @param request
* @param response
* @return
*/
public static boolean downFile(File file, HttpServletRequest request, HttpServletResponse response) {
boolean isOk = true;
OutputStream myout = null;
FileInputStream fis = null;
BufferedInputStream buff = null;
HttpSession session = request.getSession();
if (session != null) {
session.setAttribute("state", "");
}
try {
response.setContentType("application/x-msdownload");
response.setContentLength((int) file.length());
response.setHeader("content-disposition", "attachment;filename=" + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
fis = new FileInputStream(file);
buff = new BufferedInputStream(fis);
byte[] b = new byte[1024 * 10];//相當於我們的緩存
long k = 0;//該值用於計算當前實際下載了多少字節
//從response對象中得到輸出流,準備下載
myout = response.getOutputStream();
while (k < file.length()) {
int j = buff.read(b, 0, b.length);
k += j;
//將b中的數據寫到客戶端的內存
myout.write(b, 0, j);
}
myout.flush();
} catch (Exception e) {
e.printStackTrace();
isOk = false;
} finally {
try {
if (null != myout) {
myout.close();
myout = null;
}
if (null != buff) {
buff.close();
buff = null;
}
if (null != fis) {
fis.close();
fis = null;
}
if (file.exists()) {
ZipOpUtil.delFile(file);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return isOk;
}
/**
* 刪除單個文件
*
* @param file
* @return
*/
public static boolean delFile(File file) {
boolean isOk = true;
try {
if (file.isFile() && file.exists()) {
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
isOk = false;
} finally {
// log ...
}
return isOk;
}
/**
* 解壓文件到指定文件夾
*
* @param zip 源文件
* @param destPath 目標文件夾路徑
* @throws Exception 解壓失敗
*/
public static void decompress(String zip, String destPath) throws Exception {
//參數檢查
if (StringUtils.isEmpty(zip) || StringUtils.isEmpty(destPath)) {
throw new IllegalArgumentException("zip or destPath is illegal");
}
File zipFile = new File(zip);
if (!zipFile.exists()) {
throw new FileNotFoundException("zip file is not exists");
}
File destFolder = new File(destPath);
if (!destFolder.exists()) {
if (!destFolder.mkdirs()) {
throw new FileNotFoundException("destPath mkdirs is failed");
}
}
ZipInputStream zis = null;
BufferedOutputStream bos = null;
try {
zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zip),1024));
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
//得到解壓文件在當前存儲的絕對路徑
String filePath = destPath + File.separator + ze.getName();
if (ze.isDirectory()) {
new File(filePath).mkdirs();
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
}
byte[] bytes = baos.toByteArray();
File entryFile = new File(filePath);
//創建父目錄
if (!entryFile.getParentFile().exists()) {
if (!entryFile.getParentFile().mkdirs()) {
throw new FileNotFoundException("zip entry mkdirs is failed");
}
}
//寫文件
bos = new BufferedOutputStream(new FileOutputStream(entryFile));
bos.write(bytes);
bos.flush();
}
}
} finally {
closeQuietly(zis);
closeQuietly(bos);
}
}
private static void closeQuietly(final Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (final IOException ioe) {
// ignore
}
}
/**
* 上傳文件
* @param file
* @param path 文件路徑
* @return
* @throws IOException
*/
public static String upload(MultipartFile file, String path) throws IOException {
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
logger.info(String.format("upload file: %s, size: %d", fileName, size));
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判斷文件父目錄是否存在
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return fileName;
}
/**
* @Author:
* @Description:獲取某個目錄下所有直接下級文件,包括目錄下的子目錄的下的文件,所以用遞歸獲取
* @Date:
*/
public static List<String> getFiles(String path, List<String> files) {
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].toString());
//文件名,不包含路徑
//String fileName = tempList[i].getName();
}
if (tempList[i].isDirectory()) {
//這裏就不遞歸了,
getFiles(tempList[i].getPath(),files);
}
}
return files;
}
/**
* 文件複製到另一個目錄下
* @param startPath 文件所有目錄:home/upload/file/hello.java
* @param endPath 目的目錄:home/upload/
*/
public static void moveTotherFolders(String startPath,String endPath) {
File src = new File(startPath);
File dest = new File(endPath + src.getName());
// 定義文件輸入流和輸出流對象
FileInputStream fis = null;// 輸入流
FileOutputStream fos = null;// 輸出流
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
byte[] bs = new byte[1024];
while (true) {
int len = fis.read(bs, 0, bs.length);
if (len == -1) {
break;
} else {
fos.write(bs, 0, len);
}
}
System.out.println("複製文件成功");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 往文件裏寫內容
* @param list SQL集合
*/
public static String writerFile(List<String> list,String time){
String path = CommonConstant.FILE_ROOT + time + File.separator + "projectSql.sql";
try {
FileWriter fw = new FileWriter(path,false);
if(list != null && list.size() > 0){
for(int i = 0; i <list.size(); i++){
fw.write(list.get(i).toString() + ";\r\n");//windows中的換行爲\r\n unix下爲\r。
}
}else{
System.out.println("項目導出功能 - SQLList爲空");
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
}