import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.zip.*;
public class FileUtils {
private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
public static void download(File file, String fileName, HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
long modificationDate = file.lastModified();
res.setHeader("Last-Modified", modificationDate + "");
res.setHeader("cache-control", "max-age=7776000");
String mimeType = "application/octet-stream";
res.setContentType(mimeType);
String headerKey = "Content-Disposition";
String fileDateName = "";
if(fileName.indexOf(".") > -1){
fileDateName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" +
System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
} else {
fileDateName = fileName;
}
String headerValue = String.format("attachment; filename=\"%s\"", new String(fileName.getBytes(),"iso-8859-1"));
res.setHeader(headerKey, headerValue);
res.setHeader("Accept-Ranges", "bytes");
long downloadSize = file.length();
long fromPos = 0, toPos = 0;
if (req.getHeader("Range") == null) {
res.setHeader("Content-Length", downloadSize + "");
} else {
res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
String range = req.getHeader("Range");
String bytes = range.replaceAll("bytes=", "");
String[] ary = bytes.split("-");
fromPos = Long.parseLong(ary[0]);
if (ary.length == 2) {
toPos = Long.parseLong(ary[1]);
}
int size;
if (toPos > fromPos) {
size = (int) (toPos - fromPos);
} else {
size = (int) (downloadSize - fromPos);
}
res.setHeader("Content-Length", size + "");
downloadSize = size;
}
RandomAccessFile in = null;
OutputStream out = null;
try {
in = new RandomAccessFile(file, "rw");
if (fromPos > 0) {
in.seek(fromPos);
}
int bufLen = (int) (downloadSize < 2048 ? downloadSize : 2048);
byte[] buffer = new byte[bufLen];
int num;
int count = 0;
out = res.getOutputStream();
while ((num = in.read(buffer)) > 0) {
out.write(buffer, 0, num);
count += num;
if (downloadSize - count < bufLen) {
bufLen = (int) (downloadSize-count);
if(bufLen==0){
break;
}
buffer = new byte[bufLen];
}
}
res.flushBuffer();
} catch (IOException e) {
logger.error("-->下载文件出错 error msg : {}", e.getMessage());
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
logger.error("-->下载文件出错 out.close error msg : {}", e.getMessage());
}
}
if (null != in) {
try {
in.close();
} catch (IOException e) {
logger.error("-->下载文件出错 in.close error msg : {}", e.getMessage());
}
}
}
}
public static void downloadVideo(File file, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
byte[] buffer = bos.toByteArray();
response.setContentType("application/octet-stream");
response.setHeader("Accept-Ranges", "bytes");
response.setContentLength(buffer.length);
response.getOutputStream().write(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public static String getFileMd5(String filePath) throws IOException {
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(filePath);
String md5 = DigestUtils.md5Hex(fileInputStream);
fileInputStream.close();
return md5;
} catch (Exception e) {
logger.error("get file md5 error, path: {}", filePath, e);
return null;
}
}
public static boolean existFile(String filePath) {
File file;
try {
file = new File(filePath);
} catch (Exception e) {
return false;
}
return file.exists();
}
public static String zip(List<ThsZipEntry> zipEntries, String zipPath, String comment)
throws IOException {
if (zipPath == null || "".equals(zipPath) || !zipPath.endsWith(".zip")) {
throw new FileNotFoundException("必须指定一个压缩路径,而且该路径必须以'.zip'为结尾");
}
File zipFile = new File(zipPath);
if (!zipFile.getParentFile().exists()) {
zipFile.getParentFile().mkdirs();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(zipPath);
} catch (FileNotFoundException e) {
if (fos != null) {
try{ fos.close(); } catch (Exception e1) {}
}
}
CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32());
ZipOutputStream zos = new ZipOutputStream(csum);
zos.setComment(comment);
zos.setMethod(ZipOutputStream.DEFLATED);
zos.setLevel(Deflater.BEST_COMPRESSION);
BufferedOutputStream bout = null;
try {
bout = new BufferedOutputStream(zos);
for (ThsZipEntry entry : zipEntries) {
BufferedInputStream bin = null;
try{
File file = new File(entry.getEntryValue());
if (!file.exists()) {
continue;
}
if (file.isDirectory()) {
for (File child : file.listFiles()) {
String topPath = entry.getEntryValue().replaceAll("\\\\", "/");
addZipFileEntry(entry.getEntryName(), topPath, child, zos, bout);
}
} else {
ZipEntry zipEntry = new ZipEntry(entry.getEntryName());
zos.putNextEntry(zipEntry);
bin = new BufferedInputStream(new FileInputStream(entry.getEntryValue()));
byte[] buffer = new byte[1024];
int readCount = -1;
while ((readCount = bin.read(buffer)) != -1) {
bout.write(buffer, 0, readCount);
}
}
bout.flush();
zos.closeEntry();
} catch (Exception e) {
} finally {
if (bin != null) {
try { bin.close(); } catch (IOException e) {}
}
}
}
} finally {
if (bout != null) {
try{ bout.close(); } catch (Exception e) {}
}
}
return zipPath;
}
private static void addZipFileEntry(String topEntry, String topPath, File entryFile, ZipOutputStream zos, BufferedOutputStream bout) {
BufferedInputStream bin = null;
try {
if (entryFile == null || !entryFile.exists()) {
return;
}
if (entryFile.isDirectory()) {
for (File child : entryFile.listFiles()) {
addZipFileEntry(topEntry, topPath, child, zos, bout);
}
} else {
String fileEntryName = entryFile.getAbsolutePath().replaceAll("\\\\", "/").replace(topPath, "");
String fileFullEntryName = topEntry + fileEntryName;
ZipEntry zipEntry = new ZipEntry(fileFullEntryName);
zos.putNextEntry(zipEntry);
bin = new BufferedInputStream(new FileInputStream(entryFile));
byte[] buffer = new byte[1024];
int readCount = -1;
while ((readCount = bin.read(buffer)) != -1) {
bout.write(buffer, 0, readCount);
}
}
bout.flush();
zos.closeEntry();
} catch (Exception e) {
} finally {
if (bin != null) {
try { bin.close(); } catch (IOException e) {}
}
}
}
public static String unzip(String sourceZipPath, String targetPath) throws IOException {
try (ZipInputStream zip = new ZipInputStream(new FileInputStream(new File(sourceZipPath)), Charset.forName("gbk"))) {
File targetDir = new File(targetPath);
if (!targetDir.exists()) targetDir.mkdirs();
String zipFullName = new File(sourceZipPath).getName();
String zipName = zipFullName.substring(0, zipFullName.lastIndexOf("."));
ZipEntry zipEntry;
String zipEntryName;
File zipEntryFile;
while ((zipEntry = zip.getNextEntry()) != null) {
zipEntryName = zipEntry.getName();
zipEntryFile = new File(targetDir.getAbsolutePath() + "/" + zipName + "/" + zipEntryName);
if (zipEntryName.endsWith("/")) {
zipEntryFile.mkdirs();
} else {
if (!zipEntryFile.getParentFile().exists()) {
zipEntryFile.getParentFile().mkdirs();
}
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(zipEntryFile));
byte[] byte_s = new byte[1024];
int num;
while ((num = zip.read(byte_s, 0, byte_s.length)) > -1) {
outputStream.write(byte_s, 0, num);
}
outputStream.close();
}
}
return (targetDir.getAbsolutePath() + "/" + zipName).replaceAll("\\\\", "/");
} catch (Exception e) {
throw e;
}
}
public static String saveInputStream(InputStream ins, String fileSaveDirPath, String fileName) throws IOException {
OutputStream os = null;
try {
if (!fileSaveDirPath.endsWith("/")) {
fileSaveDirPath = fileSaveDirPath + "/";
}
File file = new File(fileSaveDirPath + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
return file.getAbsolutePath();
} catch (Exception e) {
throw e;
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(ins != null){
ins.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String readFile(String filePath) {
String jsonStr = "";
try {
File jsonFile = new File(filePath);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
int ch = 0;
StringBuilder sb = new StringBuilder();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static String readFile(InputStream inputsteam) {
String jsonStr = "";
try {
Reader reader = new InputStreamReader(inputsteam, StandardCharsets.UTF_8);
int ch = 0;
StringBuilder sb = new StringBuilder();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static boolean writeFile(String filePath, String content) {
File file;
FileOutputStream fos = null;
try {
file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (content == null) content = "";
fos = new FileOutputStream(file);
byte[] bytesArray = content.getBytes(StandardCharsets.UTF_8);
fos.write(bytesArray);
fos.flush();
return true;
} catch (Exception e) {
return false;
} finally {
try {
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ThsZipEntry {
private String entryName;
private String entryValue;
public String getEntryName() {
return entryName;
}
public void setEntryName(String entryName) {
this.entryName = entryName;
}
public String getEntryValue() {
return entryValue;
}
public void setEntryValue(String entryValue) {
this.entryValue = entryValue;
}
}