FileUtil.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. package jnpf.util;
  2. import jnpf.constant.GlobalConst;
  3. import jnpf.support.MyStandardMultipartFile;
  4. import lombok.Cleanup;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.apache.catalina.core.ApplicationPart;
  7. import org.apache.tomcat.util.http.fileupload.FileItem;
  8. import org.apache.tomcat.util.http.fileupload.FileItemFactory;
  9. import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import java.io.*;
  12. import java.nio.charset.StandardCharsets;
  13. import java.text.DateFormat;
  14. import java.text.DecimalFormat;
  15. import java.text.SimpleDateFormat;
  16. import java.util.ArrayList;
  17. import java.util.Arrays;
  18. import java.util.Date;
  19. import java.util.List;
  20. import java.util.zip.ZipEntry;
  21. import java.util.zip.ZipOutputStream;
  22. /**
  23. * @author JNPF开发平台组
  24. * @version V3.1.0
  25. * @copyright 引迈信息技术有限公司
  26. * @date 2021/3/16 10:51
  27. */
  28. @Slf4j
  29. public class FileUtil {
  30. /**
  31. * 判断文件夹是否存在
  32. *
  33. * @param filePath 文件地址
  34. * @return
  35. */
  36. public static boolean fileIsExists(String filePath) {
  37. File f = new File(XSSEscape.escapePath(filePath));
  38. if (!f.exists()) {
  39. return false;
  40. }
  41. return true;
  42. }
  43. /**
  44. * 判断文件是否存在
  45. *
  46. * @param filePath
  47. * @return
  48. */
  49. public static boolean fileIsFile(String filePath) {
  50. File f = new File(XSSEscape.escapePath(filePath));
  51. if (!f.isFile()) {
  52. return false;
  53. }
  54. return true;
  55. }
  56. /**
  57. * 删除tmp文件
  58. *
  59. * @param multipartFile
  60. * @return
  61. */
  62. public static boolean deleteTmp(MultipartFile multipartFile) {
  63. try {
  64. ((MyStandardMultipartFile) multipartFile).getPart().delete();
  65. return true;
  66. } catch (Exception e) {
  67. log.error("删除tmp文件失败,错误:" + e.getMessage());
  68. return false;
  69. }
  70. }
  71. /**
  72. * 创建文件
  73. *
  74. * @param filePath 文件地址
  75. * @param fileName 文件名
  76. * @return
  77. */
  78. public static boolean createFile(String filePath, String fileName) {
  79. String strFilePath = XSSEscape.escapePath(filePath + fileName);;
  80. File file = new File(XSSEscape.escapePath(filePath));
  81. if (!file.exists()) {
  82. /** 注意这里是 mkdirs()方法 可以创建多个文件夹 */
  83. file.mkdirs();
  84. }
  85. File subfile = new File(XSSEscape.escapePath(strFilePath));
  86. if (!subfile.exists()) {
  87. try {
  88. boolean b = subfile.createNewFile();
  89. return b;
  90. } catch (IOException e) {
  91. e.printStackTrace();
  92. }
  93. } else {
  94. return true;
  95. }
  96. return false;
  97. }
  98. /**
  99. * 创建文件夹
  100. *
  101. * @param filePath 文件夹地址
  102. * @return
  103. */
  104. public static void createDirs(String filePath) {
  105. File file = new File(XSSEscape.escapePath(filePath));
  106. if (!file.exists()) {
  107. /** 注意这里是 mkdirs()方法 可以创建多个文件夹 */
  108. file.mkdirs();
  109. }
  110. }
  111. /**
  112. * 遍历文件夹下当前文件
  113. *
  114. * @param file 地址
  115. */
  116. public static List<File> getFile(File file) {
  117. List<File> list = new ArrayList<>();
  118. File[] fileArray = file.listFiles();
  119. if (fileArray == null) {
  120. return list;
  121. } else {
  122. for (File f : fileArray) {
  123. if (f.isFile()) {
  124. list.add(0, f);
  125. }
  126. }
  127. }
  128. return list;
  129. }
  130. /**
  131. * 遍历文件夹下所有文件
  132. *
  133. * @param file 地址
  134. */
  135. public static List<File> getFile(File file, List<File> list) {
  136. File[] fileArray = file.listFiles();
  137. if (fileArray == null) {
  138. return list;
  139. } else {
  140. for (File f : fileArray) {
  141. if (f.isFile()) {
  142. list.add(0, f);
  143. } else {
  144. getFile(f, list);
  145. }
  146. }
  147. }
  148. return list;
  149. }
  150. /**
  151. * 删除文件或文件夹以及子文件夹和子文件等 【注意】请谨慎调用该方法,避免删除重要文件
  152. *
  153. * @param file
  154. */
  155. public static void deleteFileAll(File file) {
  156. if (file.exists()) {
  157. if (file.isFile()) {
  158. // 文件
  159. log.info(file.getAbsolutePath() + " 删除中...");
  160. file.delete();
  161. log.info("删除成功!");
  162. return;
  163. } else {
  164. // 文件夹
  165. File[] files = file.listFiles();
  166. for (int i = 0; i < files.length; i++) {
  167. deleteFileAll(files[i]);
  168. }
  169. file.delete();
  170. }
  171. } else {
  172. log.info(file.getAbsolutePath() + " 文件不存在!");
  173. }
  174. }
  175. /**
  176. * 删除单个文件
  177. *
  178. * @param filePath 文件路径
  179. */
  180. public static void deleteFile(String filePath) {
  181. File file = new File(XSSEscape.escapePath(filePath));
  182. if (file.exists() && file.isFile()) {
  183. file.delete();
  184. }
  185. }
  186. /**
  187. * 删除空文件夹、空的子文件夹
  188. *
  189. * @param file
  190. * @author cielo
  191. */
  192. public static void deleteEmptyDirectory(File file) {
  193. if (file != null && file.exists() && file.isDirectory()) {
  194. File[] files = file.listFiles();
  195. if (files != null && files.length > 0) {
  196. for (int i = 0; i < files.length; i++) {
  197. deleteEmptyDirectory(files[i]);
  198. }
  199. // 子文件夹里的删除完后,重新获取。判断空的子文件删除后,该文件夹是否为空
  200. files = file.listFiles();
  201. }
  202. if (files == null || files.length == 0) {
  203. String absolutePath = file.getAbsolutePath();
  204. file.delete();
  205. log.info("删除空文件夹!路径:" + absolutePath);
  206. }
  207. }
  208. }
  209. /**
  210. * 打开目录
  211. *
  212. * @param path
  213. */
  214. public static void open(String path) {
  215. // 打开输出目录
  216. try {
  217. String osName = System.getProperty("os.name");
  218. if (osName != null) {
  219. if (osName.contains("Mac")) {
  220. Runtime.getRuntime().exec("open " + path);
  221. } else if (osName.contains("Windows")) {
  222. Runtime.getRuntime().exec("cmd /c start " + path);
  223. } else {
  224. log.debug("文件输出目录:" + path);
  225. }
  226. }
  227. } catch (IOException e) {
  228. e.printStackTrace();
  229. }
  230. }
  231. /**
  232. * 向文件中添加内容
  233. *
  234. * @param strcontent 内容
  235. * @param filePath 地址
  236. * @param fileName 文件名
  237. */
  238. public static void writeToFile(String strcontent, String filePath, String fileName) {
  239. //生成文件夹之后,再生成文件,不然会出错
  240. String strFilePath = filePath + fileName;
  241. // 每次写入时,都换行写
  242. File subfile = new File(strFilePath);
  243. try {
  244. /** 构造函数 第二个是读写方式 */
  245. @Cleanup RandomAccessFile raf = new RandomAccessFile(subfile, "rw");
  246. /** 将记录指针移动到该文件的最后 */
  247. raf.seek(subfile.length());
  248. /** 向文件末尾追加内容 */
  249. raf.write(strcontent.getBytes());
  250. } catch (IOException e) {
  251. e.printStackTrace();
  252. }
  253. }
  254. /**
  255. * 向文件中添加内容
  256. *
  257. * @param is 内容
  258. * @param filePath 地址
  259. * @param fileName 文件名
  260. */
  261. public static void writeToFile(InputStream is, String filePath, String fileName) {
  262. //生成文件夹之后,再生成文件,不然会出错
  263. String strFilePath = filePath;
  264. // 每次写入时,都换行写
  265. File subfile = new File(XSSEscape.escapePath(strFilePath));
  266. try {
  267. @Cleanup FileOutputStream downloadFile = new FileOutputStream(subfile);
  268. int index;
  269. byte[] bytes = new byte[1024];
  270. while ((index = is.read(bytes)) != -1) {
  271. downloadFile.write(bytes, 0, index);
  272. downloadFile.flush();
  273. }
  274. } catch (IOException e) {
  275. e.printStackTrace();
  276. }
  277. }
  278. /**
  279. * 修改文件内容(覆盖或者添加)
  280. *
  281. * @param path 文件地址
  282. * @param content 覆盖内容
  283. * @param append 指定了写入的方式,是覆盖写还是追加写(true=追加)(false=覆盖)
  284. */
  285. public static void modifyFile(String path, String content, boolean append) {
  286. try {
  287. @Cleanup FileWriter fileWriter = new FileWriter(path, append);
  288. @Cleanup BufferedWriter writer = new BufferedWriter(fileWriter);
  289. writer.append(content);
  290. writer.flush();
  291. writer.close();
  292. } catch (IOException e) {
  293. e.printStackTrace();
  294. }
  295. }
  296. /**
  297. * 读取文件内容
  298. *
  299. * @param filePath 地址
  300. * @param filename 名称
  301. * @return 返回内容
  302. */
  303. public static String getString(String filePath, String filename) {
  304. try {
  305. @Cleanup FileInputStream inputStream = null;
  306. inputStream = new FileInputStream(new File(XSSEscape.escapePath(filePath + filename)));
  307. @Cleanup InputStreamReader inputStreamReader = null;
  308. inputStreamReader = new InputStreamReader(inputStream, Constants.UTF8);
  309. @Cleanup BufferedReader reader = new BufferedReader(inputStreamReader);
  310. StringBuffer sb = new StringBuffer("");
  311. String line;
  312. while ((line = reader.readLine()) != null) {
  313. sb.append(line);
  314. sb.append("\n");
  315. }
  316. return sb.toString();
  317. } catch (Exception e) {
  318. e.printStackTrace();
  319. }
  320. return "";
  321. }
  322. /**
  323. * 重命名文件
  324. *
  325. * @param oldPath 原来的文件地址
  326. * @param newPath 新的文件地址
  327. */
  328. public static void renameFile(String oldPath, String newPath) {
  329. File oleFile = new File(XSSEscape.escapePath(oldPath));
  330. File newFile = new File(XSSEscape.escapePath(newPath));
  331. //执行重命名
  332. oleFile.renameTo(newFile);
  333. }
  334. /**
  335. * 复制文件
  336. *
  337. * @param fromFile 要复制的文件目录
  338. * @param toFile 要粘贴的文件目录
  339. * @return 是否复制成功
  340. */
  341. public static boolean copy(String fromFile, String toFile) {
  342. //要复制的文件目录
  343. File[] currentFiles;
  344. File root = new File(XSSEscape.escapePath(fromFile));
  345. //如同判断SD卡是否存在或者文件是否存在
  346. //如果不存在则 return出去
  347. if (!root.exists()) {
  348. return false;
  349. }
  350. //如果存在则获取当前目录下的全部文件 填充数组
  351. currentFiles = root.listFiles();
  352. //目标目录
  353. File targetDir = new File(XSSEscape.escapePath(toFile));
  354. //创建目录
  355. if (!targetDir.exists()) {
  356. targetDir.mkdirs();
  357. }
  358. //遍历要复制该目录下的全部文件
  359. for (int i = 0; i < currentFiles.length; i++) {
  360. if (currentFiles[i].isDirectory()) {
  361. //如果当前项为子目录 进行递归
  362. copy(currentFiles[i].getPath() + "/", toFile + currentFiles[i].getName() + "/");
  363. } else {
  364. //如果当前项为文件则进行文件拷贝
  365. copyFile(currentFiles[i].getPath(), toFile + currentFiles[i].getName());
  366. }
  367. }
  368. return true;
  369. }
  370. /**
  371. * 文件拷贝
  372. * 要复制的目录下的所有非子目录(文件夹)文件拷贝
  373. *
  374. * @param fromFile
  375. * @param toFile
  376. * @return
  377. */
  378. public static boolean copyFile(String fromFile, String toFile) {
  379. try {
  380. @Cleanup InputStream fosfrom = new FileInputStream(XSSEscape.escapePath(fromFile));
  381. @Cleanup OutputStream fosto = new FileOutputStream(XSSEscape.escapePath(toFile));
  382. byte[] bt = new byte[1024];
  383. int c;
  384. while ((c = fosfrom.read(bt)) > 0) {
  385. fosto.write(bt, 0, c);
  386. }
  387. return true;
  388. } catch (Exception ex) {
  389. return false;
  390. }
  391. }
  392. /**
  393. * 文件拷贝
  394. *
  395. * @param fromFile
  396. * @param toFile
  397. * @param fileName
  398. * @return
  399. */
  400. public static boolean copyFile(String fromFile, String toFile, String fileName) {
  401. try {
  402. //目标目录
  403. File targetDir = new File(XSSEscape.escapePath(toFile));
  404. //创建目录
  405. if (!targetDir.exists()) {
  406. targetDir.mkdirs();
  407. }
  408. @Cleanup InputStream fosfrom = new FileInputStream(fromFile);
  409. @Cleanup OutputStream fosto = new FileOutputStream(toFile + fileName);
  410. byte[] bt = new byte[1024];
  411. int c;
  412. while ((c = fosfrom.read(bt)) > 0) {
  413. fosto.write(bt, 0, c);
  414. }
  415. return true;
  416. } catch (Exception ex) {
  417. return false;
  418. }
  419. }
  420. /**
  421. * 获取文件输入流
  422. */
  423. public static InputStream readFileToInputStream(String path) {
  424. InputStream inputStream = null;
  425. try {
  426. File file = new File(XSSEscape.escapePath(path));
  427. inputStream = new FileInputStream(file);
  428. } catch (IOException e) {
  429. e.getMessage();
  430. }
  431. return inputStream;
  432. }
  433. /**
  434. * 保存文件
  435. *
  436. * @param inputStream
  437. * @param path
  438. * @param fileName
  439. */
  440. public static void write(InputStream inputStream, String path, String fileName) {
  441. OutputStream os = null;
  442. long dateStr = System.currentTimeMillis();
  443. try {
  444. // 1K的数据缓冲
  445. byte[] bs = new byte[1024];
  446. // 读取到的数据长度
  447. int len;
  448. // 输出的文件流保存到本地文件
  449. File tempFile = new File(XSSEscape.escapePath(path));
  450. if (!tempFile.exists()) {
  451. tempFile.mkdirs();
  452. }
  453. String newFileName = tempFile.getPath() + File.separator + fileName;
  454. log.info("保存文件:" + newFileName);
  455. os = new FileOutputStream(XSSEscape.escapePath(newFileName));
  456. // 开始读取
  457. while ((len = inputStream.read(bs)) != -1) {
  458. os.write(bs, 0, len);
  459. }
  460. } catch (IOException e) {
  461. log.error("生成excel失败");
  462. } catch (Exception e) {
  463. log.error("生成excel失败");
  464. } finally {
  465. // 完毕,关闭所有链接
  466. try {
  467. if (os != null) {
  468. os.close();
  469. }
  470. inputStream.close();
  471. } catch (IOException e) {
  472. log.error("关闭链接失败" + e.getMessage());
  473. }
  474. }
  475. }
  476. /**
  477. * 写入文件
  478. *
  479. * @param inputStream
  480. * @param path
  481. * @param fileName
  482. */
  483. public static void writeFile(InputStream inputStream, String path, String fileName) {
  484. OutputStream os = null;
  485. try {
  486. // 1K的数据缓冲
  487. byte[] bs = new byte[1024];
  488. // 读取到的数据长度
  489. int len;
  490. // 输出的文件流保存到本地文件
  491. File tempFile = new File(XSSEscape.escapePath(path));
  492. if (!tempFile.exists()) {
  493. tempFile.mkdirs();
  494. }
  495. String newFileName = tempFile.getPath() + File.separator + fileName;
  496. log.info("保存文件:" + newFileName);
  497. os = new FileOutputStream(XSSEscape.escapePath(newFileName));
  498. // 开始读取
  499. while ((len = inputStream.read(bs)) != -1) {
  500. os.write(bs, 0, len);
  501. }
  502. } catch (IOException e) {
  503. log.error("生成excel失败");
  504. } catch (Exception e) {
  505. log.error("生成excel失败");
  506. } finally {
  507. // 完毕,关闭所有链接
  508. try {
  509. if (os != null) {
  510. os.close();
  511. }
  512. inputStream.close();
  513. } catch (IOException e) {
  514. log.error("关闭链接失败" + e.getMessage());
  515. }
  516. }
  517. }
  518. /**
  519. * 上传文件
  520. *
  521. * @param file 文件
  522. * @param filePath 保存路径
  523. * @param fileName 保存名称
  524. */
  525. public static void upFile(MultipartFile file, String filePath, String fileName) {
  526. try {
  527. // 输出的文件流保存到本地文件
  528. File tempFile = new File(XSSEscape.escapePath(filePath));
  529. if (!tempFile.exists()) {
  530. tempFile.mkdirs();
  531. }
  532. File f = new File(filePath, fileName);
  533. //将上传的文件存储到指定位置
  534. file.transferTo(f);
  535. } catch (Exception e) {
  536. log.error(e.getMessage());
  537. }
  538. }
  539. /**
  540. * 读取文件修改时间
  541. */
  542. public static String getCreateTime(String filePath) {
  543. DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  544. File file = new File(XSSEscape.escapePath(filePath));
  545. // 毫秒数
  546. long modifiedTime = file.lastModified();
  547. // 通过毫秒数构造日期 即可将毫秒数转换为日期
  548. Date date = new Date(modifiedTime);
  549. String dateString = format.format(date);
  550. return dateString;
  551. }
  552. /**
  553. * 获取文件类型
  554. */
  555. public static String getFileType(File file) {
  556. if (file.isFile()) {
  557. String fileName = file.getName();
  558. String fileTyle = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
  559. return fileTyle;
  560. }
  561. return null;
  562. }
  563. /**
  564. * 获取文件类型
  565. */
  566. public static String getFileType(String fileName) {
  567. int lastIndexOf = fileName.lastIndexOf(".") + 1;
  568. //获取文件的后缀名 jpg
  569. String suffix = fileName.substring(lastIndexOf);
  570. return suffix;
  571. }
  572. /**
  573. * 获取文件大小
  574. *
  575. * @param data
  576. * @return
  577. */
  578. public static String getSize(String data) {
  579. String size = "";
  580. if (data != null && !StringUtil.isEmpty(data)) {
  581. long fileS = Long.parseLong(data);
  582. DecimalFormat df = new DecimalFormat("#.00");
  583. if (fileS < 1024) {
  584. size = df.format((double) fileS) + "BT";
  585. } else if (fileS < 1048576) {
  586. size = df.format((double) fileS / 1024) + "KB";
  587. } else if (fileS < 1073741824) {
  588. size = df.format((double) fileS / 1048576) + "MB";
  589. } else {
  590. size = df.format((double) fileS / 1073741824) + "GB";
  591. }
  592. } else {
  593. size = "0BT";
  594. }
  595. return size;
  596. }
  597. private static final int BUFFER_SIZE = 2 * 1024;
  598. /**
  599. * 压缩文件夹
  600. *
  601. * @param srcDir 压缩文件夹路径
  602. * @param outDir 压缩文件路径
  603. * @param keepDirStructure 是否保留原来的目录结构,
  604. * true:保留目录结构;
  605. * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
  606. * @throws RuntimeException 压缩失败会抛出运行时异常
  607. */
  608. public static void toZip(String outDir, boolean keepDirStructure, String... srcDir) {
  609. try {
  610. @Cleanup OutputStream out = new FileOutputStream(new File(XSSEscape.escapePath(outDir)));
  611. @Cleanup ZipOutputStream zos = null;
  612. try {
  613. zos = new ZipOutputStream(out);
  614. List<File> sourceFileList = new ArrayList<File>();
  615. for (String dir : srcDir) {
  616. File sourceFile = new File(XSSEscape.escapePath(dir));
  617. sourceFileList.add(sourceFile);
  618. }
  619. compress(sourceFileList, zos, keepDirStructure);
  620. } catch (Exception e) {
  621. throw new RuntimeException("zip error from ZipUtils", e);
  622. }
  623. } catch (Exception e) {
  624. log.error("压缩失败:{}", e.getMessage());
  625. }
  626. }
  627. /**
  628. * 递归压缩方法
  629. *
  630. * @param sourceFile 源文件
  631. * @param zos zip输出流
  632. * @param name 压缩后的名称
  633. * @param keepDirStructure 是否保留原来的目录结构,
  634. * true:保留目录结构;
  635. * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
  636. * @throws Exception
  637. */
  638. private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean keepDirStructure) throws Exception {
  639. byte[] buf = new byte[BUFFER_SIZE];
  640. if (sourceFile.isFile()) {
  641. zos.putNextEntry(new ZipEntry(name));
  642. int len;
  643. @Cleanup FileInputStream in = new FileInputStream(sourceFile);
  644. while ((len = in.read(buf)) != -1) {
  645. zos.write(buf, 0, len);
  646. }
  647. zos.closeEntry();
  648. in.close();
  649. } else {
  650. File[] listFiles = sourceFile.listFiles();
  651. if (listFiles == null || listFiles.length == 0) {
  652. if (keepDirStructure) {
  653. zos.putNextEntry(new ZipEntry(name + "/"));
  654. zos.closeEntry();
  655. }
  656. } else {
  657. for (File file : listFiles) {
  658. if (keepDirStructure) {
  659. compress(file, zos, name + "/" + file.getName(),
  660. keepDirStructure);
  661. } else {
  662. compress(file, zos, file.getName(), keepDirStructure);
  663. }
  664. }
  665. }
  666. }
  667. }
  668. private static void compress(List<File> sourceFileList, ZipOutputStream zos, boolean keepDirStructure) throws Exception {
  669. byte[] buf = new byte[BUFFER_SIZE];
  670. for (File sourceFile : sourceFileList) {
  671. String name = sourceFile.getName();
  672. if (sourceFile.isFile()) {
  673. zos.putNextEntry(new ZipEntry(name));
  674. int len;
  675. @Cleanup FileInputStream in = new FileInputStream(sourceFile);
  676. while ((len = in.read(buf)) != -1) {
  677. zos.write(buf, 0, len);
  678. }
  679. zos.closeEntry();
  680. in.close();
  681. } else {
  682. File[] listFiles = sourceFile.listFiles();
  683. if (listFiles == null || listFiles.length == 0) {
  684. if (keepDirStructure) {
  685. zos.putNextEntry(new ZipEntry(name + "/"));
  686. zos.closeEntry();
  687. }
  688. } else {
  689. for (File file : listFiles) {
  690. if (keepDirStructure) {
  691. compress(file, zos, name + "/" + file.getName(),
  692. keepDirStructure);
  693. } else {
  694. compress(file, zos, file.getName(),
  695. keepDirStructure);
  696. }
  697. }
  698. }
  699. }
  700. }
  701. }
  702. //=================================判断文件后缀==========================
  703. /**
  704. * 允许文件类型
  705. *
  706. * @param fileType 文件所有类型
  707. * @param fileExtension 当前文件类型
  708. * @return
  709. */
  710. public static boolean fileType(String fileType, String fileExtension) {
  711. String[] allowExtension = fileType.split(",");
  712. return Arrays.asList(allowExtension).contains(fileExtension.toLowerCase());
  713. }
  714. /**
  715. * 允许图片类型
  716. *
  717. * @param imageType 图片所有类型
  718. * @param fileExtension 当前图片类型
  719. * @return
  720. */
  721. public static boolean imageType(String imageType, String fileExtension) {
  722. String[] allowExtension = imageType.split(",");
  723. return Arrays.asList(allowExtension).contains(fileExtension.toLowerCase());
  724. }
  725. /**
  726. * 允许上传大小
  727. *
  728. * @param fileSize 文件大小
  729. * @param maxSize 最大的文件
  730. * @return
  731. */
  732. public static boolean fileSize(Long fileSize, int maxSize) {
  733. if (fileSize > maxSize) {
  734. return true;
  735. }
  736. return false;
  737. }
  738. /**
  739. * 导入生成临时文件后,获取文件内容
  740. *
  741. * @param multipartFile 文件
  742. * @param filePath 路径
  743. * @return
  744. */
  745. public static String getFileContent(MultipartFile multipartFile, String filePath) {
  746. //文件名
  747. String fileName = multipartFile.getName();
  748. //上传到项目文件路径中
  749. FileUtil.upFile(multipartFile, filePath, fileName);
  750. //读取文件文件内容
  751. String fileContent = FileUtil.getString(filePath, fileName);
  752. return fileContent;
  753. }
  754. /**
  755. * 导入生成临时文件后,获取文件内容
  756. *
  757. * @param multipartFile 文件
  758. * @return
  759. */
  760. public static String getFileContent(MultipartFile multipartFile) {
  761. StringBuffer content = new StringBuffer();
  762. try {
  763. @Cleanup InputStream is = multipartFile.getInputStream();
  764. @Cleanup InputStreamReader isReader = new InputStreamReader(is, GlobalConst.DEFAULT_CHARSET);
  765. @Cleanup BufferedReader br = new BufferedReader(isReader);
  766. //循环逐行读取
  767. while (br.ready()) {
  768. content.append(br.readLine());
  769. }
  770. } catch (IOException e) {
  771. log.error(e.getMessage());
  772. }
  773. return content.toString();
  774. }
  775. /**
  776. * 判断是否为json格式且不为空
  777. * @param multipartFile
  778. * @param type 类型
  779. * @return
  780. */
  781. public static boolean existsSuffix(MultipartFile multipartFile, String type) {
  782. if (!multipartFile.getOriginalFilename().endsWith("." + type) || multipartFile.getSize()<1){
  783. return true;
  784. }
  785. return false;
  786. }
  787. /**
  788. * File转MultipartFile
  789. *
  790. * @param file
  791. * @return
  792. */
  793. public static MultipartFile createFileItem(File file) {
  794. FileItemFactory factory = new DiskFileItemFactory(16, null);
  795. FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
  796. int bytesRead = 0;
  797. byte[] buffer = new byte[8192];
  798. try {
  799. @Cleanup FileInputStream fis = new FileInputStream(file);
  800. OutputStream os = item.getOutputStream();
  801. while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
  802. os.write(buffer, 0, bytesRead);
  803. }
  804. os.close();
  805. fis.close();
  806. } catch (IOException e) {
  807. e.printStackTrace();
  808. }
  809. MultipartFile multipartFile = new MyStandardMultipartFile(new ApplicationPart(item, null), file.getName());
  810. return multipartFile;
  811. }
  812. /**
  813. * File转MultipartFile
  814. *
  815. * @param file
  816. * @return
  817. */
  818. public static MultipartFile[] createFileItems(File file) {
  819. FileItemFactory factory = new DiskFileItemFactory(16, null);
  820. FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
  821. int bytesRead = 0;
  822. byte[] buffer = new byte[8192];
  823. try {
  824. @Cleanup FileInputStream fis = new FileInputStream(file);
  825. OutputStream os = item.getOutputStream();
  826. while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
  827. os.write(buffer, 0, bytesRead);
  828. }
  829. os.close();
  830. fis.close();
  831. } catch (IOException e) {
  832. e.printStackTrace();
  833. }
  834. MultipartFile multipartFile = new MyStandardMultipartFile(new ApplicationPart(item, null), file.getName());
  835. return null;
  836. }
  837. /**
  838. * MultipartFile 转 File
  839. *
  840. * @param file
  841. * @throws Exception
  842. */
  843. public static File multipartFileToFile(MultipartFile file) {
  844. File toFile = null;
  845. if (file.getSize() > 0) {
  846. InputStream ins = null;
  847. try {
  848. ins = file.getInputStream();
  849. toFile = new File(file.getOriginalFilename());
  850. //获取流文件
  851. try {
  852. @Cleanup OutputStream os = new FileOutputStream(toFile);
  853. int bytesRead = 0;
  854. byte[] buffer = new byte[8192];
  855. while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
  856. os.write(buffer, 0, bytesRead);
  857. }
  858. os.close();
  859. ins.close();
  860. } catch (Exception e) {
  861. e.printStackTrace();
  862. }
  863. ins.close();
  864. } catch (Exception e) {
  865. log.error(e.getMessage());
  866. }
  867. }
  868. return toFile;
  869. }
  870. public static void main(String[] args) {
  871. File f = new File("E:\\Win\\UploadPE.zip");
  872. System.out.println(f.length());
  873. }
  874. }