• Java 文件处理工具类FileUtils


    1. package com.ruoyi.common.utils.file;
    2. import java.io.*;
    3. import java.net.URLEncoder;
    4. import java.nio.charset.StandardCharsets;
    5. import java.util.zip.ZipInputStream;
    6. import java.util.zip.ZipOutputStream;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import org.apache.commons.fileupload.FileItem;
    10. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    11. import org.apache.commons.io.IOUtils;
    12. import org.apache.commons.lang3.ArrayUtils;
    13. import com.ruoyi.common.config.RuoYiConfig;
    14. import com.ruoyi.common.utils.DateUtils;
    15. import com.ruoyi.common.utils.StringUtils;
    16. import com.ruoyi.common.utils.uuid.IdUtils;
    17. import org.apache.commons.io.FilenameUtils;
    18. import org.springframework.http.MediaType;
    19. import org.springframework.web.multipart.MultipartFile;
    20. import org.springframework.web.multipart.commons.CommonsMultipartFile;
    21. /**
    22. * 文件处理工具类
    23. *
    24. * @author ruoyi
    25. */
    26. public class FileUtils
    27. {
    28. public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
    29. /**
    30. * 输出指定文件的byte数组
    31. *
    32. * @param filePath 文件路径
    33. * @param os 输出流
    34. * @return
    35. */
    36. public static void writeBytes(String filePath, OutputStream os) throws IOException
    37. {
    38. FileInputStream fis = null;
    39. try
    40. {
    41. File file = new File(filePath);
    42. if (!file.exists())
    43. {
    44. throw new FileNotFoundException(filePath);
    45. }
    46. fis = new FileInputStream(file);
    47. byte[] b = new byte[1024];
    48. int length;
    49. while ((length = fis.read(b)) > 0)
    50. {
    51. os.write(b, 0, length);
    52. }
    53. }
    54. catch (IOException e)
    55. {
    56. throw e;
    57. }
    58. finally
    59. {
    60. IOUtils.close(os);
    61. IOUtils.close(fis);
    62. }
    63. }
    64. /**
    65. * 写数据到文件中
    66. *
    67. * @param data 数据
    68. * @return 目标文件
    69. * @throws IOException IO异常
    70. */
    71. public static String writeImportBytes(byte[] data) throws IOException
    72. {
    73. return writeBytes(data, RuoYiConfig.getImportPath());
    74. }
    75. /**
    76. * 写数据到文件中
    77. *
    78. * @param data 数据
    79. * @param uploadDir 目标文件
    80. * @return 目标文件
    81. * @throws IOException IO异常
    82. */
    83. public static String writeBytes(byte[] data, String uploadDir) throws IOException
    84. {
    85. FileOutputStream fos = null;
    86. String pathName = "";
    87. try
    88. {
    89. String extension = getFileExtendName(data);
    90. pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
    91. File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName);
    92. fos = new FileOutputStream(file);
    93. fos.write(data);
    94. }
    95. finally
    96. {
    97. IOUtils.close(fos);
    98. }
    99. return FileUploadUtils.getPathFileName(uploadDir, pathName);
    100. }
    101. /**
    102. * 删除文件
    103. *
    104. * @param filePath 文件
    105. * @return
    106. */
    107. public static boolean deleteFile(String filePath)
    108. {
    109. boolean flag = false;
    110. File file = new File(filePath);
    111. // 路径为文件且不为空则进行删除
    112. if (file.isFile() && file.exists())
    113. {
    114. file.delete();
    115. flag = true;
    116. }
    117. return flag;
    118. }
    119. /**
    120. * 文件名称验证
    121. *
    122. * @param filename 文件名称
    123. * @return true 正常 false 非法
    124. */
    125. public static boolean isValidFilename(String filename)
    126. {
    127. return filename.matches(FILENAME_PATTERN);
    128. }
    129. /**
    130. * 检查文件是否可下载
    131. *
    132. * @param resource 需要下载的文件
    133. * @return true 正常 false 非法
    134. */
    135. public static boolean checkAllowDownload(String resource)
    136. {
    137. // 禁止目录上跳级别
    138. if (StringUtils.contains(resource, ".."))
    139. {
    140. return false;
    141. }
    142. // 检查允许下载的文件规则
    143. if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource)))
    144. {
    145. return true;
    146. }
    147. // 不在允许下载的文件规则
    148. return false;
    149. }
    150. /**
    151. * 下载文件名重新编码
    152. *
    153. * @param request 请求对象
    154. * @param fileName 文件名
    155. * @return 编码后的文件名
    156. */
    157. public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
    158. {
    159. final String agent = request.getHeader("USER-AGENT");
    160. String filename = fileName;
    161. if (agent.contains("MSIE"))
    162. {
    163. // IE浏览器
    164. filename = URLEncoder.encode(filename, "utf-8");
    165. filename = filename.replace("+", " ");
    166. }
    167. else if (agent.contains("Firefox"))
    168. {
    169. // 火狐浏览器
    170. filename = new String(fileName.getBytes(), "ISO8859-1");
    171. }
    172. else if (agent.contains("Chrome"))
    173. {
    174. // google浏览器
    175. filename = URLEncoder.encode(filename, "utf-8");
    176. }
    177. else
    178. {
    179. // 其它浏览器
    180. filename = URLEncoder.encode(filename, "utf-8");
    181. }
    182. return filename;
    183. }
    184. /**
    185. * 下载文件名重新编码
    186. *
    187. * @param response 响应对象
    188. * @param realFileName 真实文件名
    189. */
    190. public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
    191. {
    192. String percentEncodedFileName = percentEncode(realFileName);
    193. StringBuilder contentDispositionValue = new StringBuilder();
    194. contentDispositionValue.append("attachment; filename=")
    195. .append(percentEncodedFileName)
    196. .append(";")
    197. .append("filename*=")
    198. .append("utf-8''")
    199. .append(percentEncodedFileName);
    200. response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
    201. response.setHeader("Content-disposition", contentDispositionValue.toString());
    202. response.setHeader("download-filename", percentEncodedFileName);
    203. }
    204. /**
    205. * 百分号编码工具方法
    206. *
    207. * @param s 需要百分号编码的字符串
    208. * @return 百分号编码后的字符串
    209. */
    210. public static String percentEncode(String s) throws UnsupportedEncodingException
    211. {
    212. String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
    213. return encode.replaceAll("\\+", "%20");
    214. }
    215. /**
    216. * 获取图像后缀
    217. *
    218. * @param photoByte 图像数据
    219. * @return 后缀名
    220. */
    221. public static String getFileExtendName(byte[] photoByte)
    222. {
    223. String strFileExtendName = "jpg";
    224. if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
    225. && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97))
    226. {
    227. strFileExtendName = "gif";
    228. }
    229. else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
    230. {
    231. strFileExtendName = "jpg";
    232. }
    233. else if ((photoByte[0] == 66) && (photoByte[1] == 77))
    234. {
    235. strFileExtendName = "bmp";
    236. }
    237. else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
    238. {
    239. strFileExtendName = "png";
    240. }
    241. return strFileExtendName;
    242. }
    243. /**
    244. * 获取文件名称 /profile/upload/2022/04/16/ruoyi.png -- ruoyi.png
    245. *
    246. * @param fileName 路径名称
    247. * @return 没有文件路径的名称
    248. */
    249. public static String getName(String fileName)
    250. {
    251. if (fileName == null)
    252. {
    253. return null;
    254. }
    255. int lastUnixPos = fileName.lastIndexOf('/');
    256. int lastWindowsPos = fileName.lastIndexOf('\\');
    257. int index = Math.max(lastUnixPos, lastWindowsPos);
    258. return fileName.substring(index + 1);
    259. }
    260. /**
    261. * 获取不带后缀文件名称 /profile/upload/2022/04/16/ruoyi.png -- ruoyi
    262. *
    263. * @param fileName 路径名称
    264. * @return 没有文件路径和后缀的名称
    265. */
    266. public static String getNameNotSuffix(String fileName)
    267. {
    268. if (fileName == null)
    269. {
    270. return null;
    271. }
    272. String baseName = FilenameUtils.getBaseName(fileName);
    273. return baseName;
    274. }
    275. //File转MultipartFile
    276. public static MultipartFile getMultipartFile(File file) {
    277. FileItem item = new DiskFileItemFactory().createItem("file"
    278. , MediaType.MULTIPART_FORM_DATA_VALUE
    279. , true
    280. , file.getName());
    281. try (InputStream input = new FileInputStream(file);
    282. OutputStream os = item.getOutputStream()) {
    283. // 流转移
    284. IOUtils.copy(input, os);
    285. } catch (Exception e) {
    286. throw new IllegalArgumentException("Invalid file: " + e, e);
    287. }
    288. return new CommonsMultipartFile(item);
    289. }
    290. //路径校验不存在就创建对应的目录
    291. public static void filePath(String path){
    292. File file = new File(path);
    293. // 判断路径是否存在,不存在创建
    294. if (!file.exists()) {
    295. file.mkdirs();
    296. }
    297. }
    298. /**
    299. * 复制 文件或者文件夹
    300. * @param oldPath
    301. * @param newPath
    302. * @throws IOException
    303. */
    304. public static void copyFile(String oldPath ,String newPath ){
    305. System.out.println("copy file from [" + oldPath + "] to [" + newPath +"]");
    306. try {
    307. File oldFile = new File(oldPath) ;
    308. if (oldFile.exists()) {
    309. if(oldFile.isDirectory()){ // 如果是文件夹
    310. File newPathDir = new File(newPath);
    311. newPathDir.mkdirs();
    312. File[] lists = oldFile.listFiles() ;
    313. if(lists != null && lists.length > 0 ){
    314. for (File file : lists) {
    315. copyFile(file.getAbsolutePath(), newPath.endsWith(File.separator) ? newPath + file.getName() : newPath + File.separator + file.getName()) ;
    316. }
    317. }
    318. }else {
    319. InputStream inStream = new FileInputStream(oldFile); //读入原文件
    320. FileOutputStream fs = new FileOutputStream(newPath);
    321. write2Out(inStream ,fs) ;
    322. inStream.close();
    323. }
    324. }
    325. }catch (Exception e){
    326. System.out.println("复制文件到新路径失败:"+e.getMessage());
    327. }
    328. }
    329. public static void copeZipFile(String oldPath ,String newPath) throws Exception {
    330. FileInputStream fin = new FileInputStream(new File(oldPath));
    331. ZipInputStream zin = new ZipInputStream(fin);
    332. byte[] in_bytes = new byte[1000];
    333. zin.read(in_bytes,0,1000);
    334. FileOutputStream fout = new FileOutputStream(new File(newPath));
    335. ZipOutputStream zout = new ZipOutputStream(fout);
    336. zout.write(in_bytes,0,in_bytes.length);
    337. fin.close();
    338. zin.close();
    339. fout.close();
    340. zout.close();
    341. }
    342. /**
    343. *
    344. *
    345. * @param url 指定文件的位置
    346. * @param content 异常输出的内容
    347. * @throws Exception
    348. */
    349. public static void writeFile(String url, String content) throws Exception {
    350. File file = new File(url);
    351. FileWriter fw = null;
    352. //文件不存在创建新文件
    353. if (!file.exists()) {
    354. file.createNewFile();
    355. }else{
    356. FileUtils.deleteFile(url);
    357. file.createNewFile();
    358. }
    359. String writeDate = content;
    360. try {
    361. fw = new FileWriter(file, true);
    362. fw.write(writeDate + "\r\n");
    363. } catch (Exception e) {
    364. e.printStackTrace();
    365. } finally {
    366. if (fw != null) {
    367. fw.close();
    368. }
    369. }
    370. }
    371. /**
    372. * 重命名文件
    373. * @param file
    374. * @param name
    375. * @return
    376. */
    377. public static File renameFile(File file , String name ){
    378. String fileName = file.getParent() + File.separator + name ;
    379. File dest = new File(fileName);
    380. file.renameTo(dest) ;
    381. return dest ;
    382. }
    383. private static void write2Out(InputStream input , OutputStream out) throws IOException {
    384. byte[] b = new byte[1024];
    385. int c = 0 ;
    386. while ( (c = input.read(b)) != -1 ) {
    387. out.write(b,0,c);
    388. out.flush();
    389. }
    390. out.flush();
    391. }
    392. /**
    393. * File转MultipartFile
    394. * @param file
    395. * @return
    396. */
    397. public static MultipartFile getMultipartFile(File file) {
    398. FileItem item = new DiskFileItemFactory().createItem("file"
    399. , MediaType.MULTIPART_FORM_DATA_VALUE
    400. , true
    401. , file.getName());
    402. try (InputStream input = new FileInputStream(file);
    403. OutputStream os = item.getOutputStream()) {
    404. // 流转移
    405. IOUtils.copy(input, os);
    406. } catch (Exception e) {
    407. throw new IllegalArgumentException("Invalid file: " + e, e);
    408. }
    409. return new CommonsMultipartFile(item);
    410. }
    411. /**
    412. * 将MultipartFile转换为File
    413. * @param multiFile
    414. * @return
    415. */
    416. public static File MultipartFileToFile(MultipartFile multiFile) {
    417. // 获取文件名
    418. String fileName = multiFile.getOriginalFilename();
    419. // 获取文件后缀
    420. String prefix = fileName.substring(fileName.lastIndexOf("."));
    421. // 若须要防止生成的临时文件重复,能够在文件名后添加随机码
    422. try {
    423. File file = File.createTempFile(fileName, prefix);
    424. multiFile.transferTo(file);
    425. return file;
    426. } catch (Exception e) {
    427. e.printStackTrace();
    428. }
    429. return null;
    430. }
    431. /**
    432. * File进行Base64编码
    433. * @param file
    434. * @return
    435. * @throws Exception
    436. */
    437. public static String encodeBase64File(File file) throws Exception {
    438. //File file = new File(path);
    439. FileInputStream inputFile = new FileInputStream(file);
    440. byte[] buffer = new byte[(int)file.length()];
    441. inputFile.read(buffer);
    442. inputFile.close();
    443. return new BASE64Encoder().encode(buffer);
    444. }
    445. }

    1. //将公包复制一份到当前登陆账户的私有路径下 并修改压缩包名称
    2. org.apache.commons.io.FileUtils.copyFile(new File(zpiPath),new File(zipurl));

  • 相关阅读:
    Leetcode290. 单词规律
    One Last Kiss风格封面生成器;程序内存分析工具;Python入门课程资料;神经文本语音合成教程;前沿论文 | ShowMeAI资讯日报
    【Python练习】task-06 函数的练习和实验
    网页布局常用的8种布局方式
    Flask 学习-61.Flask-Mail 发送邮件
    精简100倍的jar打包方法
    软考-信息系统项目管理师- 第 1 章 信息化和信息系统基础知识
    pycharm统计代码运行时间
    Docker安装
    sql语句优化总结-避免全表扫描
  • 原文地址:https://blog.csdn.net/yyongsheng/article/details/126901573