檔案工具類 FileUtils
阿新 • • 發佈:2021-02-05
技術標籤:javaspringboot上傳下載
import cn.hutool.core.date.DateUtil;
import com.tsms.common.utils.StringUtils;
import com.tsms.common.utils.file.FileTypeUtils;
import com.tsms.common.utils.file.MimeTypeUtils;
import org.apache.commons.lang3.ArrayUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
/**
* 檔案工具類
*
* @author 雲諾
* @Description:
* @date 2021/1/11 5:34
* @Version
*/
public class FileUtil {
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
/**
* 輸出指定檔案的byte陣列
*
* @param filePath 檔案路徑
* @param os 輸出流
* @return
*/
public static void writeBytes(String filePath, OutputStream os) throws IOException
{
FileInputStream fis = null;
try
{
File file = new File(filePath);
if (!file.exists())
{
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0)
{
os.write(b, 0, length);
}
}
catch (IOException e)
{
throw e;
}
finally
{
if (os != null)
{
try
{
os.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (fis != null)
{
try
{
fis.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
/**
* 刪除檔案
*
* @param filePath 檔案
* @return
*/
public static boolean deleteFile(String filePath)
{
boolean flag = false;
File file = new File(filePath);
// 路徑為檔案且不為空則進行刪除
if (file.isFile() && file.exists())
{
file.delete();
flag = true;
}
return flag;
}
/**
* 檔名稱驗證
*
* @param filename 檔名稱
* @return true 正常 false 非法
*/
public static boolean isValidFilename(String filename)
{
return filename.matches(FILENAME_PATTERN);
}
/**
* 檢查檔案是否可下載
*
* @param resource 需要下載的檔案
* @return true 正常 false 非法
*/
public static boolean checkAllowDownload(String resource)
{
// 禁止目錄上跳級別
if (StringUtils.contains(resource, ".."))
{
return false;
}
// 檢查允許下載的檔案規則
if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource)))
{
return true;
}
// 不在允許下載的檔案規則
return false;
}
/**
* 下載檔名重新編碼
*
* @param request 請求物件
* @param fileName 檔名
* @return 編碼後的檔名
*/
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
{
final String agent = request.getHeader("USER-AGENT");
String filename = fileName;
if (agent.contains("MSIE"))
{
// IE瀏覽器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
}
else if (agent.contains("Firefox"))
{
// 火狐瀏覽器
filename = new String(fileName.getBytes(), "ISO8859-1");
}
else if (agent.contains("Chrome"))
{
// google瀏覽器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
}
else
{
// 其它瀏覽器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
}
return filename;
}
/**
* 下載檔名重新編碼
*
* @param response 響應物件
* @param realFileName 真實檔名
* @return
*/
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
{
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
response.setHeader("Content-disposition", contentDispositionValue.toString());
}
/**
* 百分號編碼工具方法
*
* @param s 需要百分號編碼的字串
* @return 百分號編碼後的字串
*/
public static String percentEncode(String s) throws UnsupportedEncodingException
{
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20");
}
/**
* @param filePath: 檔案路徑
* @Description: 獲取檔案建立時間
* @Author: 雲諾
* @date 2021/1/11 5:35
* @return: java.lang.String 檔案建立時間,若無法獲取建立時間(linux中),返回檔案修改時間
*/
public static String getFileCreateTime(String filePath) {
File file = new File(filePath);
try {
Path path = Paths.get(filePath);
BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
BasicFileAttributes attr = basicview.readAttributes();
long l = attr.creationTime().toMillis();
Date date = new Date(l);
String createtime = DateUtil.formatDateTime(date);
return createtime;
} catch (Exception e) {
// 獲取建立時間失敗,返回修改時間
long l = file.lastModified();
Date date = new Date(l);
String modifiedTime = DateUtil.formatDateTime(date);
return modifiedTime;
}
}
/**
* 輸出指定檔案的byte陣列
*
* @param fis 檔案輸入流
* @param os 輸出流
* @return
* @Title: writeBytes
* @Description:
* @author 雲諾
*/
public static void writeBytes(InputStream fis, OutputStream os) throws IOException {
try {
if (fis == null) {
throw new FileNotFoundException();
}
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0) {
os.write(b, 0, length);
}
} catch (IOException e) {
throw e;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}