1. package com.hikvision.idatafusion.psbddatachange.common.util;
    2. import com.hikvision.idatafusion.exception.BusinessException;
    3. import com.hikvision.idatafusion.psbddatachange.common.constant.PsbddatachangeErrorCode;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.apache.commons.lang3.StringUtils;
    6. import org.slf4j.Logger;
    7. import org.slf4j.LoggerFactory;
    8. import org.springframework.core.io.ClassPathResource;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.*;
    11. import java.net.URLEncoder;
    12. import java.nio.charset.StandardCharsets;
    13. /**
    14. * 文件工具类
    15. *
    16. * @author 韩仁松
    17. * @since businessV1.0.0
    18. */
    19. @Slf4j
    20. public class FileUtil {
    21. private final static Logger logger = LoggerFactory.getLogger(FileUtil.class);
    22. private final static int DEFAULT_BUFFER_SIZE = 1024;
    23. private final static String LEFT_SLASH = "/";
    24. /**
    25. * 读取UTF-8资源文件内容
    26. *
    27. * @param name 资源文件的路径
    28. * @param clazz 加载资源文件的class
    29. * @return 返回读取的资源文件内容,异常时返回null
    30. */
    31. public static String getUTF8ResourceAsString(String name, Class clazz) {
    32. return getResourceAsString(name, clazz, StandardCharsets.UTF_8.name());
    33. }
    34. /**
    35. * 读取资源文件内容
    36. *
    37. * @param name 资源文件的路径
    38. * @param clazz 加载资源文件的class
    39. * @param charsetName 加载文件的字符集
    40. * @return 返回读取的资源文件内容,异常时返回null
    41. */
    42. private static String getResourceAsString(String name, Class clazz, String charsetName) {
    43. if (!name.startsWith(LEFT_SLASH)) {
    44. name = LEFT_SLASH + name;
    45. }
    46. try (InputStream in = clazz.getResourceAsStream(name)) {
    47. return streamToString(in, charsetName);
    48. } catch (IOException e) {
    49. logger.error("load resource file error: {}, and load class: {}", name, clazz.getName());
    50. return null;
    51. }
    52. }
    53. /**
    54. * InputStream转化为String
    55. *
    56. * @param in InputStream数据流
    57. * @param charsetName 加载文件的字符集
    58. * @return 返回转化后的字符串
    59. * @throws IOException 读取异常转抛
    60. */
    61. private static String streamToString(InputStream in, String charsetName) throws IOException {
    62. try (ByteArrayOutputStream result = new ByteArrayOutputStream()) {
    63. byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    64. int length;
    65. while ((length = in.read(buffer)) != -1) {
    66. result.write(buffer, 0, length);
    67. }
    68. return result.toString(charsetName);
    69. } catch (IOException e) {
    70. throw e;
    71. }
    72. }
    73. /**
    74. * 读取资源文件内容
    75. *
    76. * @param name 资源文件的路径
    77. * @return 返回读取的资源文件内容,异常时返回null
    78. */
    79. public static String getResourceAsStringByPath(String name) {
    80. if (!name.startsWith(LEFT_SLASH)) {
    81. name = LEFT_SLASH + name;
    82. }
    83. ClassPathResource resource = new ClassPathResource(name);
    84. if(!resource.exists()){
    85. resource = new ClassPathResource("/config" + name);
    86. }
    87. try (InputStream in = resource.getInputStream()) {
    88. return streamToString(in, StandardCharsets.UTF_8.name());
    89. } catch (IOException e) {
    90. log.error("load resource file error: {},", name);
    91. return null;
    92. }
    93. }
    94. public static void inputStreamToFile(InputStream in, File file){
    95. try {
    96. OutputStream os = new FileOutputStream(file);
    97. int bytes = 0;
    98. byte[] buffer = new byte[1024];
    99. while ((bytes = in.read(buffer, 0, buffer.length)) != -1){
    100. os.write(buffer, 0 ,bytes);
    101. }
    102. os.close();
    103. in.close();
    104. } catch (Exception e) {
    105. e.printStackTrace();
    106. }
    107. }
    108. public static boolean download(HttpServletResponse response, File file) {
    109. String fileName = file.getName();
    110. try {
    111. fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
    112. } catch (UnsupportedEncodingException e) {
    113. //log.error(PsbddatachangeLogHelper.message(PsbddatachangeErrorCode.FILE_READ_ERROR, "file name encoder error:"+ fileName), e);
    114. }
    115. response.setContentType("application/octet-stream");
    116. response.setHeader("Content-Disposition", String.format("attachment;filename=%s", fileName));
    117. response.setContentLength((int) file.length());
    118. response.addHeader("Content-Length", String.valueOf(file.length()));
    119. InputStream is = null;
    120. OutputStream out = null;
    121. byte[] bytes = new byte[2048];
    122. int count = 0;
    123. try {
    124. is = new FileInputStream(file);
    125. out = response.getOutputStream();
    126. while ((count = is.read(bytes)) > 0) {
    127. out.write(bytes, 0, count);
    128. }
    129. return true;
    130. } catch (IOException e) {
    131. //log.error(PsbddatachangeLogHelper.message(PsbddatachangeErrorCode.FILE_WRITE_ERROR, "download file error:"+ file.getAbsolutePath()), e);
    132. return false;
    133. } finally {
    134. try {
    135. if (is != null) {
    136. is.close();
    137. }
    138. if (out != null) {
    139. out.close();
    140. }
    141. if(file!=null && file.exists()) {
    142. file.delete();
    143. }
    144. } catch (IOException e) {
    145. //log.error(PsbddatachangeLogHelper.message(PsbddatachangeErrorCode.A_FILE_CLOSE_ERROR, "i/o close failed"), e);
    146. }
    147. }
    148. }
    149. public static boolean download(HttpServletResponse response, InputStream is, String fileName) {
    150. try {
    151. fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
    152. } catch (UnsupportedEncodingException e) {
    153. }
    154. response.setContentType("application/octet-stream");
    155. response.setHeader("Content-Disposition", String.format("attachment;filename=%s", fileName));
    156. OutputStream out = null;
    157. byte[] bytes = new byte[2048];
    158. int count = 0;
    159. try {
    160. out = response.getOutputStream();
    161. while ((count = is.read(bytes)) > 0) {
    162. out.write(bytes, 0, count);
    163. }
    164. out.flush();
    165. return true;
    166. } catch (IOException e) {
    167. log.error(PsbddatachangeErrorCode.FILE_WRITE_ERROR, "download file error:"+fileName, e);
    168. return false;
    169. } finally {
    170. try {
    171. if (is != null) {
    172. is.close();
    173. }
    174. if (out != null) {
    175. out.close();
    176. }
    177. } catch (IOException e) {
    178. log.error(PsbddatachangeErrorCode.A_FILE_CLOSE_ERROR, "i/o close failed", e);
    179. }
    180. }
    181. }
    182. /**
    183. * dirName 只有下载文件到本地的时候才有用
    184. *
    185. * @param response
    186. */
    187. public static boolean downloadV2(HttpServletResponse response, InputStream is, String fileName) {
    188. try {
    189. fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
    190. } catch (UnsupportedEncodingException e) {
    191. //throw new BusinessException(PsbddatachangeErrorCode.IO_ERROR, "download_template_failed", e);
    192. }
    193. response.setContentType("application/octet-stream");
    194. response.setHeader("Content-Disposition", String.format("attachment;filename=%s", fileName));
    195. OutputStream out = null;
    196. byte[] bytes = new byte[2048];
    197. int count = 0;
    198. try {
    199. out = response.getOutputStream();
    200. while ((count = is.read(bytes)) > 0) {
    201. out.write(bytes, 0, count);
    202. }
    203. out.flush();
    204. return true;
    205. } catch (IOException e) {
    206. //throw new BusinessException(PsbddatachangeErrorCode.IO_ERROR, "download_template_failed", e);
    207. } finally {
    208. try {
    209. if (is != null) {
    210. is.close();
    211. }
    212. if (out != null) {
    213. out.close();
    214. }
    215. } catch (IOException e) {
    216. //throw new BusinessException(PsbddatachangeErrorCode.A_FILE_CLOSE_ERROR, "download_template_failed", e);
    217. }
    218. }
    219. return true;
    220. }
    221. public static String getResourceAsStringByClassPathResource(String path){
    222. return getResourceAsStringByClassPathResource(path, StandardCharsets.UTF_8.name());
    223. }
    224. public static String getResourceAsStringByClassPathResource(String path,String charsetName){
    225. if(StringUtils.isEmpty(path)) {
    226. log.info(PsbddatachangeLogHelper.message("path is null..."));
    227. return null;
    228. }
    229. if(StringUtils.isEmpty(charsetName)) {
    230. log.info(PsbddatachangeLogHelper.message("charsetName is null..."));
    231. return null;
    232. }
    233. ClassPathResource resource = new ClassPathResource(path);
    234. if(!resource.exists()) {
    235. log.info(PsbddatachangeLogHelper.message("resource not exists..."));
    236. return null;
    237. }
    238. try {
    239. return getStringByStream(resource.getInputStream(),charsetName);
    240. } catch (IOException e) {
    241. log.error(PsbddatachangeLogHelper.message("load resource file error: {} "), path);
    242. return null;
    243. }
    244. }
    245. public static String getStringByStream(InputStream in, String charsetName) throws IOException {
    246. ByteArrayOutputStream result = new ByteArrayOutputStream();
    247. try{
    248. byte[] buffer = new byte[1024];
    249. int length;
    250. while ((length = in.read(buffer)) != -1) {
    251. result.write(buffer, 0, length);
    252. }
    253. return result.toString(charsetName);
    254. } catch (IOException e) {
    255. throw e;
    256. }finally {
    257. if(in!=null) {
    258. in.close();
    259. }
    260. if(result!=null) {
    261. result.close();
    262. }
    263. }
    264. }
    265. public static boolean download(HttpServletResponse response, File file, String fileName, boolean isDelete) {
    266. try {
    267. fileName = URLEncoder.encode(fileName, "UTF-8");
    268. } catch (UnsupportedEncodingException e) {
    269. log.error(PsbddatachangeLogHelper.message("file name encoder error:" + fileName), e);
    270. }
    271. response.setContentType("application/octet-stream;charset=utf-8");
    272. response.setHeader("Content-Disposition", String.format("attachment;filename=%s", fileName));
    273. response.setContentLength((int) file.length());
    274. response.addHeader("Content-Length", String.valueOf(file.length()));
    275. InputStream is = null;
    276. OutputStream out = null;
    277. byte[] bytes = new byte[2048];
    278. int count = 0;
    279. try {
    280. is = new FileInputStream(file);
    281. out = response.getOutputStream();
    282. while ((count = is.read(bytes)) > 0) {
    283. out.write(bytes, 0, count);
    284. }
    285. out.flush();
    286. // return true;
    287. } catch (IOException e) {
    288. log.error(PsbddatachangeLogHelper.message("download file error:" + file.getAbsolutePath()), e);
    289. return false;
    290. } finally {
    291. try {
    292. if (is != null) {
    293. is.close();
    294. }
    295. if (out != null) {
    296. out.close();
    297. }
    298. if (file != null && file.exists() && isDelete) {
    299. file.delete();
    300. }
    301. } catch (IOException e) {
    302. log.error(PsbddatachangeLogHelper.message("i/o close failed"), e);
    303. }
    304. }
    305. return true;
    306. }
    307. public static boolean download(HttpServletResponse response, File file, boolean isDelete) {
    308. return download(response, file, file.getName(), isDelete);
    309. }
    310. /**
    311. * 获取文件名称后缀
    312. *
    313. * @param fileName 文件名
    314. * @return String
    315. */
    316. public static String getSuffix(String fileName) {
    317. if (fileName.contains(".")) {
    318. return fileName.substring(fileName.lastIndexOf(".") + 1);
    319. } else {
    320. return "";
    321. }
    322. }
    323. public static void downloadFileInClassPath(HttpServletResponse response, String fileNameInClassPath, String outFileName) {
    324. ClassPathResource resource = new ClassPathResource("template/" + fileNameInClassPath);
    325. try {
    326. downloadV2(response, resource.getInputStream(),outFileName);
    327. } catch (IOException e) {
    328. throw new BusinessException(PsbddatachangeErrorCode.FILE_DOWNLOAD_ERROR, e);
    329. }
    330. }
    331. }