FileUtils.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. package com.example.fms.common.utils;
  2. import cn.hutool.core.io.FileUtil;
  3. import cn.hutool.core.util.IdUtil;
  4. import com.alibaba.fastjson.JSONArray;
  5. import com.alibaba.fastjson.JSONObject;
  6. import com.example.fms.common.model.dto.SystemFileDTO;
  7. import com.example.fms.common.model.dto.UploadFileDTO;
  8. import okhttp3.*;
  9. import okhttp3.Response;
  10. import org.apache.commons.compress.utils.IOUtils;
  11. import org.apache.commons.fileupload.FileItem;
  12. import org.apache.commons.fileupload.disk.DiskFileItem;
  13. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.boot.system.ApplicationHome;
  16. import org.springframework.mock.web.MockMultipartFile;
  17. import org.springframework.stereotype.Service;
  18. import org.springframework.web.multipart.MultipartFile;
  19. import org.springframework.web.multipart.commons.CommonsMultipartFile;
  20. import java.io.*;
  21. import java.net.URL;
  22. import java.nio.file.Files;
  23. import java.util.Collections;
  24. import java.util.List;
  25. import java.util.Objects;
  26. import java.util.concurrent.TimeUnit;
  27. import static cn.hutool.core.io.FileUtil.getMimeType;
  28. @Service
  29. public class FileUtils {
  30. public static final String FILE_SEPARATOR = System.getProperty("file.separator");
  31. public static final String COMMON_FILE = "file";
  32. public static final String BACKUP_FILE = "backup";
  33. @Autowired
  34. private FileUtils fileUtils;
  35. public static String getStaticPath(String fileName) {
  36. //ApplicationHome类 返回target目录层级
  37. ApplicationHome ah = new ApplicationHome(FileUtils.class);
  38. //获取 applicationHome 内的路径 ...\target\classes 到这一层级下
  39. File file = ah.getSource();
  40. //获取 file的parentFile 即最后一级之前的所有层级路径(包括盘符) 这里能获得到的最终层级为 ...\target 后续用FILE_SEPARATOR(系统路径分割通配符 即 "\") 以及fileName拼接生成存放文件的目录层级 即为根目录 root
  41. String rootPath = file.getParentFile().toString() + FILE_SEPARATOR + fileName;
  42. //根据上方生成的根目录路径 生成对应文件夹 没有就新建
  43. File root = new File(rootPath);
  44. if (!root.exists()) {
  45. root.mkdir();
  46. }
  47. //返回的最终形式为 盘符:\项目层级\target\file
  48. return rootPath;
  49. }
  50. public UploadFileDTO uploadFile(MultipartFile file) {
  51. UploadFileDTO fileDTO = new UploadFileDTO();
  52. //以下操作为 先取得传入文件的完整文件名 (文件名 + 后缀) 然后用FileUtil分别取出 文件名 和 不带 "." 的后缀 然后将这些内容装配进 实体中
  53. //file.getOriginFilename 获取源文件
  54. //FileUtil.getPrefix 返回主文件名
  55. fileDTO.setName(FileUtil.getPrefix(file.getOriginalFilename()));
  56. //FileUtil.extName 获取文件的扩展名(后缀名),扩展名不带 "."
  57. fileDTO.setExtName(FileUtil.extName(file.getOriginalFilename()));
  58. //获取目录名 用时间作为目录名称
  59. String directoryName = this.getDirectoryName();
  60. //用IdUtil生成的UUID 与实体中的 extName(后缀名) 拼接后作为文件名 simpleUUID与randomUUID的区别是 simpleUUID 没有 "-"
  61. String fileName = IdUtil.simpleUUID() + "." + fileDTO.getExtName();
  62. //将完整文件名进行装配
  63. fileDTO.setFileName(fileName);
  64. //生成存储文件的路径
  65. String savePath = this.getSavePath(directoryName);
  66. //根据生成存储文件的路径 生成对应文件夹 没有就新建
  67. File directory = new File(savePath);
  68. if (!directory.exists()) {
  69. directory.mkdir();
  70. }
  71. this.saveFile(file, savePath + fileName);
  72. fileDTO.setPath(FILE_SEPARATOR + directoryName + FILE_SEPARATOR + fileName);
  73. fileDTO.setFileSize(file.getSize());
  74. return fileDTO;
  75. }
  76. public SystemFileDTO getFileInfo(MultipartFile file) {
  77. SystemFileDTO systemFileDTO = new SystemFileDTO();
  78. //以下操作为 先取得传入文件的完整文件名 (文件名 + 后缀) 然后用FileUtil分别取出 文件名 和 不带 "." 的后缀 然后将这些内容装配进 实体中
  79. //file.getOriginFilename 获取源文件
  80. //FileUtil.getPrefix 返回主文件名
  81. systemFileDTO.setFileName(FileUtil.getPrefix(file.getOriginalFilename()));
  82. return systemFileDTO;
  83. }
  84. public String createDirectory() {
  85. String directoryName = this.getDirectoryName();
  86. String savePath = this.getSavePath(directoryName);
  87. File directory = new File(savePath);
  88. if (!directory.exists()) {
  89. directory.mkdir();
  90. }
  91. return directoryName;
  92. }
  93. public void saveFile(MultipartFile file, String path) {
  94. try {
  95. file.transferTo(new File(path));
  96. } catch (Exception e) {
  97. e.printStackTrace();
  98. }
  99. }
  100. public String getTempPath(String fileName) {
  101. String tempPath = getStaticPath(COMMON_FILE) + FILE_SEPARATOR + "temp";
  102. File file = new File(tempPath);
  103. if (!file.exists()) {
  104. file.mkdir();
  105. }
  106. return tempPath + FILE_SEPARATOR + fileName;
  107. }
  108. public String getSavePath(String directoryName) {
  109. return getStaticPath(COMMON_FILE) + FILE_SEPARATOR + directoryName + FILE_SEPARATOR;
  110. }
  111. public String getDirectory(String fileName) {
  112. return FILE_SEPARATOR + this.createDirectory() + FILE_SEPARATOR + fileName;
  113. }
  114. public String getDirectory2(String directoryName) {
  115. return FILE_SEPARATOR + directoryName + FILE_SEPARATOR;
  116. }
  117. public String getSystemPath(String url) {
  118. return getStaticPath(COMMON_FILE) + FILE_SEPARATOR + url;
  119. }
  120. public String getSystemPath() {
  121. return getStaticPath(COMMON_FILE);
  122. }
  123. public String getPath(String url) {
  124. return getStaticPath(COMMON_FILE) + url;
  125. }
  126. public static MultipartFile fileToMultipartFile(File file) {
  127. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(16, null);
  128. FileItem item = diskFileItemFactory.createItem(file.getName(), "text/plain", true, file.getName());
  129. int bytesRead = 0;
  130. byte[] buffer = new byte[8192];
  131. try {
  132. FileInputStream fis = new FileInputStream(file);
  133. OutputStream os = item.getOutputStream();
  134. int len = 8192;
  135. while ((bytesRead = fis.read(buffer, 0, len)) != -1) {
  136. os.write(buffer, 0, bytesRead);
  137. }
  138. os.close();
  139. fis.close();
  140. } catch (IOException e) {
  141. e.printStackTrace();
  142. }
  143. return (MultipartFile) new CommonsMultipartFile(item);
  144. }
  145. public static File getFile(String url, String fileName) throws Exception {
  146. String name = "";
  147. if (fileName.contains(".")) {
  148. name = fileName.substring(0, fileName.indexOf("."));
  149. }
  150. //读取图片类型
  151. String fileType = url.substring(url.lastIndexOf("."), url.length());
  152. File file = null;
  153. URL urlfile;
  154. InputStream inStream = null;
  155. OutputStream os = null;
  156. try {
  157. file = File.createTempFile(name, fileType);
  158. //获取文件
  159. urlfile = new URL(url);
  160. inStream = urlfile.openStream();
  161. os = new FileOutputStream(file);
  162. int bytesRead = 0;
  163. byte[] buffer = new byte[8192];
  164. while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
  165. os.write(buffer, 0, bytesRead);
  166. }
  167. } catch (Exception e) {
  168. e.printStackTrace();
  169. } finally {
  170. try {
  171. if (null != os) {
  172. os.close();
  173. }
  174. if (null != inStream) {
  175. inStream.close();
  176. }
  177. } catch (Exception e) {
  178. e.printStackTrace();
  179. }
  180. }
  181. return file;
  182. }
  183. public static File getFile1(String url, String fileName) throws Exception {
  184. String name = "";
  185. if (fileName.contains(".")) {
  186. name = fileName.substring(0, fileName.indexOf("."));
  187. }
  188. //读取图片类型
  189. String fileType = url.substring(url.lastIndexOf("."), url.length());
  190. File file = null;
  191. URL urlfile;
  192. InputStream inStream = null;
  193. OutputStream os = null;
  194. try {
  195. file = new File(name + fileType);
  196. //获取文件
  197. urlfile = new URL(url);
  198. inStream = urlfile.openStream();
  199. os = new FileOutputStream(file);
  200. int bytesRead = 0;
  201. byte[] buffer = new byte[8192];
  202. while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
  203. os.write(buffer, 0, bytesRead);
  204. }
  205. } catch (Exception e) {
  206. e.printStackTrace();
  207. } finally {
  208. try {
  209. if (null != os) {
  210. os.close();
  211. }
  212. if (null != inStream) {
  213. inStream.close();
  214. }
  215. } catch (Exception e) {
  216. e.printStackTrace();
  217. }
  218. }
  219. return file;
  220. }
  221. public static File urlToFile(String fileUrl) {
  222. String path = System.getProperty("user.dir");
  223. File tmpFile = new File(path, "tmp");
  224. if (!tmpFile.exists()) {
  225. tmpFile.mkdirs();
  226. }
  227. return urlToFile(fileUrl, tmpFile);
  228. }
  229. /**
  230. * @param fileUrl 资源地址
  231. * @param tmpFile 临时文件
  232. * @Description: 网络资源转file, 用完以后必须删除该临时文件
  233. * @return: 返回值
  234. */
  235. public static File urlToFile(String fileUrl, File tmpFile) {
  236. String fileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
  237. FileOutputStream downloadFile = null;
  238. InputStream openStream = null;
  239. File savedFile = null;
  240. try {
  241. savedFile = new File(tmpFile.getAbsolutePath() + fileName);
  242. URL url = new URL(fileUrl);
  243. java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
  244. openStream = connection.getInputStream();
  245. int index;
  246. byte[] bytes = new byte[1024];
  247. downloadFile = new FileOutputStream(savedFile);
  248. while ((index = openStream.read(bytes)) != -1) {
  249. downloadFile.write(bytes, 0, index);
  250. downloadFile.flush();
  251. }
  252. } catch (Exception e) {
  253. e.printStackTrace();
  254. } finally {
  255. try {
  256. if (openStream != null) {
  257. openStream.close();
  258. }
  259. if (downloadFile != null) {
  260. downloadFile.close();
  261. }
  262. } catch (Exception e) {
  263. e.printStackTrace();
  264. }
  265. }
  266. return savedFile;
  267. }
  268. public static MultipartFile urlToMultipartFile(String url, String fileName) throws Exception {
  269. File file = FileUtils.getFile1(url, fileName);
  270. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(16, null);
  271. FileItem item = diskFileItemFactory.createItem(file.getName(), "text/plain", true, file.getName());
  272. int bytesRead = 0;
  273. byte[] buffer = new byte[8192];
  274. try {
  275. FileInputStream fis = new FileInputStream(file);
  276. OutputStream os = item.getOutputStream();
  277. int len = 8192;
  278. while ((bytesRead = fis.read(buffer, 0, len)) != -1) {
  279. os.write(buffer, 0, bytesRead);
  280. }
  281. os.close();
  282. fis.close();
  283. } catch (IOException e) {
  284. e.printStackTrace();
  285. }
  286. return new CommonsMultipartFile(item);
  287. }
  288. public UploadFileDTO uploadToLocal(String url, String type) throws Exception {
  289. MultipartFile file = FileUtils.urlToMultipartFile(url, type);
  290. UploadFileDTO fileDTO = fileUtils.uploadFile(file);
  291. return fileDTO;
  292. }
  293. public static String readerMethod() throws IOException {
  294. String ah = FileUtils.getStaticPath("setting.json");
  295. File file = new File(ah);
  296. FileReader fileReader = new FileReader(file);
  297. Reader reader = new InputStreamReader(new FileInputStream(file), "Utf-8");
  298. int ch = 0;
  299. StringBuffer sb = new StringBuffer();
  300. while ((ch = reader.read()) != -1) {
  301. sb.append((char) ch);
  302. }
  303. fileReader.close();
  304. reader.close();
  305. String jsonStr = sb.toString();
  306. return jsonStr;
  307. }
  308. public static File multipartFileToFile(MultipartFile file) throws Exception {
  309. File toFile = null;
  310. if (file.equals("") || file.getSize() <= 0) {
  311. file = null;
  312. } else {
  313. InputStream ins = null;
  314. ins = file.getInputStream();
  315. toFile = new File(file.getOriginalFilename());
  316. inputStreamToFile(ins, toFile);
  317. ins.close();
  318. }
  319. return toFile;
  320. }
  321. //获取流文件
  322. private static void inputStreamToFile(InputStream ins, File file) {
  323. try {
  324. OutputStream os = new FileOutputStream(file);
  325. int bytesRead = 0;
  326. byte[] buffer = new byte[8192];
  327. while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
  328. os.write(buffer, 0, bytesRead);
  329. }
  330. os.close();
  331. ins.close();
  332. } catch (Exception e) {
  333. e.printStackTrace();
  334. }
  335. }
  336. public String getDirectoryName() {
  337. return DateUtils.getNowTimeFormat("yyyyMMdd");
  338. }
  339. public static String getDateDirectoryName() {
  340. return DateUtils.getNowTimeFormat("yyyyMMdd");
  341. }
  342. public static boolean deleteQuietly(final File file) {
  343. if (file == null) {
  344. return false;
  345. }
  346. try {
  347. if (file.isDirectory()) {
  348. cleanDirectory(file);
  349. }
  350. } catch (final Exception ignored) {
  351. }
  352. try {
  353. return file.delete();
  354. } catch (final Exception ignored) {
  355. return false;
  356. }
  357. }
  358. public static void cleanDirectory(final File directory) throws IOException {
  359. final File[] files = verifiedListFiles(directory);
  360. IOException exception = null;
  361. for (final File file : files) {
  362. try {
  363. forceDelete(file);
  364. } catch (final IOException ioe) {
  365. exception = ioe;
  366. }
  367. }
  368. if (null != exception) {
  369. throw exception;
  370. }
  371. }
  372. private static File[] verifiedListFiles(final File directory) throws IOException {
  373. if (!directory.exists()) {
  374. final String message = directory + " does not exist";
  375. throw new IllegalArgumentException(message);
  376. }
  377. if (!directory.isDirectory()) {
  378. final String message = directory + " is not a directory";
  379. throw new IllegalArgumentException(message);
  380. }
  381. final File[] files = directory.listFiles();
  382. if (files == null) { // null if security restricted
  383. throw new IOException("Failed to list contents of " + directory);
  384. }
  385. return files;
  386. }
  387. public static void forceDelete(final File file) throws IOException {
  388. if (file.isDirectory()) {
  389. deleteDirectory(file);
  390. } else {
  391. final boolean filePresent = file.exists();
  392. if (!file.delete()) {
  393. if (!filePresent) {
  394. throw new FileNotFoundException("File does not exist: " + file);
  395. }
  396. final String message =
  397. "Unable to delete file: " + file;
  398. throw new IOException(message);
  399. }
  400. }
  401. }
  402. public static void deleteDirectory(final File directory) throws IOException {
  403. if (!directory.exists()) {
  404. return;
  405. }
  406. if (!isSymlink(directory)) {
  407. cleanDirectory(directory);
  408. }
  409. if (!directory.delete()) {
  410. final String message =
  411. "Unable to delete directory " + directory + ".";
  412. throw new IOException(message);
  413. }
  414. }
  415. public static boolean isSymlink(final File file) throws IOException {
  416. if (file == null) {
  417. throw new NullPointerException("File must not be null");
  418. }
  419. return Files.isSymbolicLink(file.toPath());
  420. }
  421. public static String getFileExrName(String fileName) {
  422. if (fileName == null || fileName.trim().equals("")) {
  423. return "";
  424. }
  425. String exrName = fileName.substring(fileName.indexOf("."), fileName.length());
  426. return exrName;
  427. }
  428. public static String getDateFilePath(String path) {
  429. String directoryName = FileUtils.getDateDirectoryName();
  430. String rePath = path + directoryName+"/";
  431. return rePath;
  432. }
  433. }