FileUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package com.fdkankan.common.util;
  2. import cn.hutool.core.collection.CollUtil;
  3. import com.fdkankan.common.constant.ErrorCode;
  4. import com.fdkankan.common.exception.BusinessException;
  5. import java.io.*;
  6. import java.nio.ByteBuffer;
  7. import java.nio.MappedByteBuffer;
  8. import java.nio.channels.FileChannel;
  9. import java.nio.channels.FileChannel.MapMode;
  10. import java.nio.charset.Charset;
  11. import java.util.ArrayList;
  12. import java.util.Enumeration;
  13. import java.util.List;
  14. import java.util.zip.ZipEntry;
  15. import java.util.zip.ZipException;
  16. import java.util.zip.ZipFile;
  17. import java.util.zip.ZipInputStream;
  18. import java.util.zip.ZipOutputStream;
  19. import lombok.extern.slf4j.Slf4j;
  20. /**
  21. * @author MeepoGuan
  22. *
  23. * <p>Description: file_util</p>
  24. *
  25. * 2017年4月30日
  26. *
  27. */
  28. @Slf4j
  29. public class FileUtil {
  30. /* public static void main(String[] args) {
  31. String dirName = "d:/FH/topic/";// 创建目录
  32. FileUtil.createDir(dirName);
  33. }*/
  34. /**
  35. * 创建目录
  36. *
  37. * @param destDirName
  38. * 目标目录名
  39. * @return 目录创建成功返回true,否则返回false
  40. */
  41. public static boolean createDir(String destDirName) {
  42. File dir = new File(destDirName);
  43. if (dir.exists()) {
  44. return false;
  45. }
  46. if (!destDirName.endsWith(File.separator)) {
  47. destDirName = destDirName + File.separator;
  48. }
  49. // 创建单个目录
  50. if (dir.mkdirs()) {
  51. return true;
  52. } else {
  53. return false;
  54. }
  55. }
  56. /**
  57. * 删除文件
  58. *
  59. * @param filePathAndName
  60. * String 文件路径及名称 如c:/fqf.txt
  61. * @return boolean
  62. */
  63. public static void delFile(String filePathAndName) {
  64. try {
  65. String filePath = filePathAndName;
  66. filePath = filePath.toString();
  67. File myDelFile = new File(filePath);
  68. myDelFile.delete();
  69. } catch (Exception e) {
  70. System.out.println("删除文件操作出错");
  71. e.printStackTrace();
  72. }
  73. }
  74. /**
  75. * 读取到字节数组0
  76. *
  77. * @param filePath //路径
  78. * @throws IOException
  79. */
  80. public static byte[] getContent(String filePath) throws IOException {
  81. File file = new File(filePath);
  82. long fileSize = file.length();
  83. if (fileSize > Integer.MAX_VALUE) {
  84. System.out.println("file too big...");
  85. return null;
  86. }
  87. FileInputStream fi = new FileInputStream(file);
  88. byte[] buffer = new byte[(int) fileSize];
  89. int offset = 0;
  90. int numRead = 0;
  91. while (offset < buffer.length
  92. && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
  93. offset += numRead;
  94. }
  95. // 确保所有数据均被读取
  96. if (offset != buffer.length) {
  97. throw new IOException("Could not completely read file "
  98. + file.getName());
  99. }
  100. fi.close();
  101. return buffer;
  102. }
  103. /**
  104. * 读取到字节数组1
  105. *
  106. * @param filePath
  107. * @return
  108. * @throws IOException
  109. */
  110. public static byte[] toByteArray(String filePath) throws IOException {
  111. File f = new File(filePath);
  112. if (!f.exists()) {
  113. throw new FileNotFoundException(filePath);
  114. }
  115. ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
  116. BufferedInputStream in = null;
  117. try {
  118. in = new BufferedInputStream(new FileInputStream(f));
  119. int buf_size = 1024;
  120. byte[] buffer = new byte[buf_size];
  121. int len = 0;
  122. while (-1 != (len = in.read(buffer, 0, buf_size))) {
  123. bos.write(buffer, 0, len);
  124. }
  125. return bos.toByteArray();
  126. } catch (IOException e) {
  127. e.printStackTrace();
  128. throw e;
  129. } finally {
  130. try {
  131. in.close();
  132. } catch (IOException e) {
  133. e.printStackTrace();
  134. }
  135. bos.close();
  136. }
  137. }
  138. /**
  139. * 读取到字节数组2
  140. *
  141. * @param filePath
  142. * @return
  143. * @throws IOException
  144. */
  145. public static byte[] toByteArray2(String filePath) throws IOException {
  146. File f = new File(filePath);
  147. if (!f.exists()) {
  148. throw new FileNotFoundException(filePath);
  149. }
  150. FileChannel channel = null;
  151. FileInputStream fs = null;
  152. try {
  153. fs = new FileInputStream(f);
  154. channel = fs.getChannel();
  155. ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
  156. while ((channel.read(byteBuffer)) > 0) {
  157. // do nothing
  158. // System.out.println("reading");
  159. }
  160. return byteBuffer.array();
  161. } catch (IOException e) {
  162. e.printStackTrace();
  163. throw e;
  164. } finally {
  165. try {
  166. channel.close();
  167. } catch (IOException e) {
  168. e.printStackTrace();
  169. }
  170. try {
  171. fs.close();
  172. } catch (IOException e) {
  173. e.printStackTrace();
  174. }
  175. }
  176. }
  177. /**
  178. * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
  179. *
  180. * @param filePath
  181. * @return
  182. * @throws IOException
  183. */
  184. public static byte[] toByteArray3(String filePath) throws IOException {
  185. FileChannel fc = null;
  186. RandomAccessFile rf = null;
  187. try {
  188. rf = new RandomAccessFile(filePath, "r");
  189. fc = rf.getChannel();
  190. MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
  191. fc.size()).load();
  192. //System.out.println(byteBuffer.isLoaded());
  193. byte[] result = new byte[(int) fc.size()];
  194. if (byteBuffer.remaining() > 0) {
  195. // System.out.println("remain");
  196. byteBuffer.get(result, 0, byteBuffer.remaining());
  197. }
  198. return result;
  199. } catch (IOException e) {
  200. e.printStackTrace();
  201. throw e;
  202. } finally {
  203. try {
  204. rf.close();
  205. fc.close();
  206. } catch (IOException e) {
  207. e.printStackTrace();
  208. }
  209. }
  210. }
  211. public static File[] sort(File[] s) {
  212. //中间值
  213. File temp = null;
  214. //外循环:我认为最小的数,从0~长度-1
  215. for (int j = 0; j < s.length - 1; j++) {
  216. //最小值:假设第一个数就是最小的
  217. String min = s[j].getName();
  218. //记录最小数的下标的
  219. int minIndex = j;
  220. //内循环:拿我认为的最小的数和后面的数一个个进行比较
  221. for (int k = j + 1; k < s.length; k++) {
  222. //找到最小值
  223. if (Integer.parseInt(min.substring(0, min.indexOf("."))) > Integer.parseInt(s[k].getName().substring(0, s[k].getName().indexOf(".")))) {
  224. //修改最小
  225. min = s[k].getName();
  226. minIndex = k;
  227. }
  228. }
  229. //当退出内层循环就找到这次的最小值
  230. //交换位置
  231. temp = s[j];
  232. s[j] = s[minIndex];
  233. s[minIndex] = temp;
  234. }
  235. return s;
  236. }
  237. /**
  238. * 获取目录下所有文件
  239. * @param directory
  240. */
  241. public static List<String> getFileList(String directory) {
  242. File f = new File(directory);
  243. File[] files = f.listFiles();
  244. if(files == null || files.length == 0){
  245. return null;
  246. }
  247. List<String> list = new ArrayList<>();
  248. for (int i = 0; i < files.length; i++) {
  249. if (files[i].isFile()) {
  250. list.add(files[i].getAbsolutePath());
  251. } else {
  252. System.out.println("目录:" + files[i]);
  253. List<String> fileList = getFileList(files[i].getAbsolutePath());
  254. if(CollUtil.isEmpty(fileList)){
  255. continue;
  256. }
  257. list.addAll(fileList);
  258. }
  259. }
  260. return list;
  261. }
  262. /**
  263. * <p>
  264. zip包解压缩
  265. * </p>
  266. * @author dengsixing
  267. * @date 2022/2/16
  268. * @param inputFile 解压文件路径
  269. * @param destDirPath 解压目标目录
  270. **/
  271. public static void unZip(String inputFile,String destDirPath) throws Exception{
  272. File srcFile = new File(inputFile);//获取当前压缩文件
  273. // 判断源文件是否存在
  274. if (!srcFile.exists()) {
  275. throw new Exception("文件不存在:" + srcFile.getPath());
  276. }
  277. try(
  278. //创建压缩文件对象
  279. ZipFile zipFile = new ZipFile(srcFile, Charset.forName("GBK"))
  280. ){
  281. //开始解压
  282. Enumeration<?> entries = zipFile.entries();
  283. while (entries.hasMoreElements()) {
  284. ZipEntry entry = (ZipEntry) entries.nextElement();
  285. // 如果是文件夹,就创建个文件夹
  286. if (entry.isDirectory()) {
  287. String dirPath = destDirPath + "/" + entry.getName();
  288. srcFile.mkdirs();
  289. } else {
  290. // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
  291. File targetFile = new File(destDirPath + "/" + entry.getName());
  292. // 保证这个文件的父文件夹必须要存在
  293. if (!targetFile.getParentFile().exists()) {
  294. targetFile.getParentFile().mkdirs();
  295. }
  296. targetFile.createNewFile();
  297. // 将压缩文件内容写入到这个文件中
  298. try(InputStream is = zipFile.getInputStream(entry);
  299. FileOutputStream fos = new FileOutputStream(targetFile)){
  300. int len;
  301. byte[] buf = new byte[1024];
  302. while ((len = is.read(buf)) != -1) {
  303. fos.write(buf, 0, len);
  304. }
  305. }catch (IOException e){
  306. log.error("解压缩失败,文件名称" + entry.getName(), e);
  307. throw e;
  308. }
  309. }
  310. }
  311. } catch (ZipException e) {
  312. log.error("解压缩失败,文件路径:" + srcFile.getPath(), e);
  313. throw e;
  314. } catch (IOException e) {
  315. log.error("解压缩失败,文件路径:" + srcFile.getPath(), e);
  316. throw e;
  317. }
  318. }
  319. /**
  320. * <p>
  321. 打包
  322. * </p>
  323. * @author dengsixing
  324. * @date 2022/2/16
  325. * @param inputFile
  326. * @param outputFile
  327. * @param withDir
  328. **/
  329. public static void zip(String inputFile, String outputFile, boolean withDir) throws Exception {
  330. try(
  331. //创建zip输出流
  332. ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
  333. //创建缓冲输出流
  334. BufferedOutputStream bos = new BufferedOutputStream(out);
  335. ){
  336. File input = new File(inputFile);
  337. compress(out, bos, input, null, withDir);
  338. }
  339. }
  340. /**
  341. * @param name 压缩文件名,可以写为null保持默认
  342. */
  343. //递归压缩
  344. public static void compress(ZipOutputStream out, BufferedOutputStream bos, File input, String name, boolean withDir) throws IOException {
  345. if (name == null) {
  346. name = input.getName();
  347. }
  348. //如果路径为目录(文件夹)
  349. if (input.isDirectory()) {
  350. //取出文件夹中的文件(或子文件夹)
  351. File[] flist = input.listFiles();
  352. if (flist.length == 0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入
  353. {
  354. if(withDir){
  355. out.putNextEntry(new ZipEntry(name + "/"));
  356. }
  357. } else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
  358. {
  359. for (int i = 0; i < flist.length; i++) {
  360. if(withDir){
  361. compress(out, bos, flist[i], name + "/" + flist[i].getName(), withDir);
  362. }else{
  363. compress(out, bos, flist[i], flist[i].getName(), withDir);
  364. }
  365. }
  366. }
  367. }
  368. //如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
  369. else
  370. {
  371. out.putNextEntry(new ZipEntry(name));
  372. FileInputStream fos = new FileInputStream(input);
  373. BufferedInputStream bis = new BufferedInputStream(fos);
  374. int len;
  375. //将源文件写入到zip文件中
  376. byte[] buf = new byte[1024];
  377. while ((len = bis.read(buf)) != -1) {
  378. bos.write(buf,0,len);
  379. }
  380. bis.close();
  381. fos.close();
  382. }
  383. }
  384. public static void main(String[] args) throws Exception {
  385. FileUtil.unZip("F:\\test\\KJ-t-VJNe28ZImv_images_展厅全景图.zip", "F:\\test\\aaa");
  386. }
  387. }