package com.hikvision.idatafusion.psbddatachange.common.util;
import com.hikvision.idatafusion.exception.BusinessException;
import com.hikvision.idatafusion.psbddatachange.common.constant.PsbddatachangeErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* 文件工具类
*
* @author 韩仁松
* @since businessV1.0.0
*/
@Slf4j
public class FileUtil {
private final static Logger logger = LoggerFactory.getLogger(FileUtil.class);
private final static int DEFAULT_BUFFER_SIZE = 1024;
private final static String LEFT_SLASH = "/";
/**
* 读取UTF-8资源文件内容
*
* @param name 资源文件的路径
* @param clazz 加载资源文件的class
* @return 返回读取的资源文件内容,异常时返回null
*/
public static String getUTF8ResourceAsString(String name, Class clazz) {
return getResourceAsString(name, clazz, StandardCharsets.UTF_8.name());
}
/**
* 读取资源文件内容
*
* @param name 资源文件的路径
* @param clazz 加载资源文件的class
* @param charsetName 加载文件的字符集
* @return 返回读取的资源文件内容,异常时返回null
*/
private static String getResourceAsString(String name, Class clazz, String charsetName) {
if (!name.startsWith(LEFT_SLASH)) {
name = LEFT_SLASH + name;
}
try (InputStream in = clazz.getResourceAsStream(name)) {
return streamToString(in, charsetName);
} catch (IOException e) {
logger.error("load resource file error: {}, and load class: {}", name, clazz.getName());
return null;
}
}
/**
* InputStream转化为String
*
* @param in InputStream数据流
* @param charsetName 加载文件的字符集
* @return 返回转化后的字符串
* @throws IOException 读取异常转抛
*/
private static String streamToString(InputStream in, String charsetName) throws IOException {
try (ByteArrayOutputStream result = new ByteArrayOutputStream()) {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = in.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(charsetName);
} catch (IOException e) {
throw e;
}
}
/**
* 读取资源文件内容
*
* @param name 资源文件的路径
* @return 返回读取的资源文件内容,异常时返回null
*/
public static String getResourceAsStringByPath(String name) {
if (!name.startsWith(LEFT_SLASH)) {
name = LEFT_SLASH + name;
}
ClassPathResource resource = new ClassPathResource(name);
if(!resource.exists()){
resource = new ClassPathResource("/config" + name);
}
try (InputStream in = resource.getInputStream()) {
return streamToString(in, StandardCharsets.UTF_8.name());
} catch (IOException e) {
log.error("load resource file error: {},", name);
return null;
}
}
public static void inputStreamToFile(InputStream in, File file){
try {
OutputStream os = new FileOutputStream(file);
int bytes = 0;
byte[] buffer = new byte[1024];
while ((bytes = in.read(buffer, 0, buffer.length)) != -1){
os.write(buffer, 0 ,bytes);
}
os.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean download(HttpServletResponse response, File file) {
String fileName = file.getName();
try {
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
//log.error(PsbddatachangeLogHelper.message(PsbddatachangeErrorCode.FILE_READ_ERROR, "file name encoder error:"+ fileName), e);
}
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", String.format("attachment;filename=%s", fileName));
response.setContentLength((int) file.length());
response.addHeader("Content-Length", String.valueOf(file.length()));
InputStream is = null;
OutputStream out = null;
byte[] bytes = new byte[2048];
int count = 0;
try {
is = new FileInputStream(file);
out = response.getOutputStream();
while ((count = is.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
return true;
} catch (IOException e) {
//log.error(PsbddatachangeLogHelper.message(PsbddatachangeErrorCode.FILE_WRITE_ERROR, "download file error:"+ file.getAbsolutePath()), e);
return false;
} finally {
try {
if (is != null) {
is.close();
}
if (out != null) {
out.close();
}
if(file!=null && file.exists()) {
file.delete();
}
} catch (IOException e) {
//log.error(PsbddatachangeLogHelper.message(PsbddatachangeErrorCode.A_FILE_CLOSE_ERROR, "i/o close failed"), e);
}
}
}
public static boolean download(HttpServletResponse response, InputStream is, String fileName) {
try {
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
}
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", String.format("attachment;filename=%s", fileName));
OutputStream out = null;
byte[] bytes = new byte[2048];
int count = 0;
try {
out = response.getOutputStream();
while ((count = is.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
return true;
} catch (IOException e) {
log.error(PsbddatachangeErrorCode.FILE_WRITE_ERROR, "download file error:"+fileName, e);
return false;
} finally {
try {
if (is != null) {
is.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
log.error(PsbddatachangeErrorCode.A_FILE_CLOSE_ERROR, "i/o close failed", e);
}
}
}
/**
* dirName 只有下载文件到本地的时候才有用
*
* @param response
*/
public static boolean downloadV2(HttpServletResponse response, InputStream is, String fileName) {
try {
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
//throw new BusinessException(PsbddatachangeErrorCode.IO_ERROR, "download_template_failed", e);
}
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", String.format("attachment;filename=%s", fileName));
OutputStream out = null;
byte[] bytes = new byte[2048];
int count = 0;
try {
out = response.getOutputStream();
while ((count = is.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
return true;
} catch (IOException e) {
//throw new BusinessException(PsbddatachangeErrorCode.IO_ERROR, "download_template_failed", e);
} finally {
try {
if (is != null) {
is.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
//throw new BusinessException(PsbddatachangeErrorCode.A_FILE_CLOSE_ERROR, "download_template_failed", e);
}
}
return true;
}
public static String getResourceAsStringByClassPathResource(String path){
return getResourceAsStringByClassPathResource(path, StandardCharsets.UTF_8.name());
}
public static String getResourceAsStringByClassPathResource(String path,String charsetName){
if(StringUtils.isEmpty(path)) {
log.info(PsbddatachangeLogHelper.message("path is null..."));
return null;
}
if(StringUtils.isEmpty(charsetName)) {
log.info(PsbddatachangeLogHelper.message("charsetName is null..."));
return null;
}
ClassPathResource resource = new ClassPathResource(path);
if(!resource.exists()) {
log.info(PsbddatachangeLogHelper.message("resource not exists..."));
return null;
}
try {
return getStringByStream(resource.getInputStream(),charsetName);
} catch (IOException e) {
log.error(PsbddatachangeLogHelper.message("load resource file error: {} "), path);
return null;
}
}
public static String getStringByStream(InputStream in, String charsetName) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
try{
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(charsetName);
} catch (IOException e) {
throw e;
}finally {
if(in!=null) {
in.close();
}
if(result!=null) {
result.close();
}
}
}
public static boolean download(HttpServletResponse response, File file, String fileName, boolean isDelete) {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error(PsbddatachangeLogHelper.message("file name encoder error:" + fileName), e);
}
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition", String.format("attachment;filename=%s", fileName));
response.setContentLength((int) file.length());
response.addHeader("Content-Length", String.valueOf(file.length()));
InputStream is = null;
OutputStream out = null;
byte[] bytes = new byte[2048];
int count = 0;
try {
is = new FileInputStream(file);
out = response.getOutputStream();
while ((count = is.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
// return true;
} catch (IOException e) {
log.error(PsbddatachangeLogHelper.message("download file error:" + file.getAbsolutePath()), e);
return false;
} finally {
try {
if (is != null) {
is.close();
}
if (out != null) {
out.close();
}
if (file != null && file.exists() && isDelete) {
file.delete();
}
} catch (IOException e) {
log.error(PsbddatachangeLogHelper.message("i/o close failed"), e);
}
}
return true;
}
public static boolean download(HttpServletResponse response, File file, boolean isDelete) {
return download(response, file, file.getName(), isDelete);
}
/**
* 获取文件名称后缀
*
* @param fileName 文件名
* @return String
*/
public static String getSuffix(String fileName) {
if (fileName.contains(".")) {
return fileName.substring(fileName.lastIndexOf(".") + 1);
} else {
return "";
}
}
public static void downloadFileInClassPath(HttpServletResponse response, String fileNameInClassPath, String outFileName) {
ClassPathResource resource = new ClassPathResource("template/" + fileNameInClassPath);
try {
downloadV2(response, resource.getInputStream(),outFileName);
} catch (IOException e) {
throw new BusinessException(PsbddatachangeErrorCode.FILE_DOWNLOAD_ERROR, e);
}
}
}