FileUtils.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. package com.fdkankan.common.util;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.io.FileUtil;
  4. import cn.hutool.core.io.IORuntimeException;
  5. import cn.hutool.core.util.ZipUtil;
  6. import cn.hutool.http.HttpUtil;
  7. import com.alibaba.fastjson.JSON;
  8. import com.alibaba.fastjson.JSONObject;
  9. import it.sauronsoftware.jave.*;
  10. import org.bytedeco.javacpp.opencv_core;
  11. import org.bytedeco.javacv.FFmpegFrameGrabber;
  12. import org.bytedeco.javacv.Frame;
  13. import org.bytedeco.javacv.Java2DFrameConverter;
  14. import org.bytedeco.javacv.OpenCVFrameConverter;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import sun.misc.BASE64Decoder;
  18. import javax.imageio.ImageIO;
  19. import java.awt.*;
  20. import java.awt.image.BufferedImage;
  21. import java.io.*;
  22. import java.net.URLDecoder;
  23. import java.nio.ByteBuffer;
  24. import java.nio.MappedByteBuffer;
  25. import java.nio.channels.FileChannel;
  26. import java.nio.charset.StandardCharsets;
  27. import java.util.List;
  28. import java.util.*;
  29. import java.util.stream.Collectors;
  30. public class FileUtils {
  31. private static Logger log = LoggerFactory.getLogger(FileUtils.class);
  32. public static byte[] getImageByte(String base64Data){
  33. byte[] bt = null;
  34. try {
  35. sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
  36. if (base64Data.startsWith("data:image/png;base64,")) {
  37. return decoder.decodeBuffer(base64Data.replace("data:image/png;base64,", ""));
  38. } else if (base64Data.startsWith("data:image/jpeg;base64,")) {
  39. return decoder.decodeBuffer(base64Data.replace("data:image/jpeg;base64,", ""));
  40. } else if (base64Data.startsWith("data:image/bmp;base64,")) {
  41. return decoder.decodeBuffer(base64Data.replace("data:image/bmp;base64,", ""));
  42. } else {
  43. return bt;
  44. }
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. return bt;
  49. }
  50. public static void uploadImg(String path, String base64Data){
  51. byte[] bt = getImageByte(base64Data);
  52. writeBinary(bt, path);
  53. }
  54. private static void writeBinary(byte[] buf, String filePath) {
  55. FileUtil.writeBytes(buf,filePath);
  56. }
  57. public static boolean createDir(String destDirName) {
  58. FileUtil.mkdir(destDirName);
  59. return true;
  60. }
  61. /**
  62. * 创建文件
  63. * @param fileName 文件名称
  64. * @param fileContent 文件内容
  65. * @return 是否创建成功,成功则返回true
  66. */
  67. public static boolean createFile(String path, String fileName,String fileContent){
  68. String fileNameTemp = path+fileName+".json";//文件路径+名称+文件类型
  69. File file = new File(fileNameTemp);
  70. if(!file.exists()){
  71. FileUtil.appendUtf8String(fileContent,fileNameTemp);
  72. log.info("success create file:{}",fileNameTemp);
  73. return true;
  74. }
  75. return false;
  76. }
  77. /**
  78. * 向文件中写入内容
  79. * @param filePath 文件路径与名称
  80. * @param newstr 写入的内容
  81. * @return
  82. * @throws IOException
  83. */
  84. public static boolean writeFileContent(String filePath, String newstr) throws IOException{
  85. Boolean bool = false;
  86. String filein = newstr+"\r\n";//新写入的行,换行
  87. String temp = "";
  88. FileInputStream fis = null;
  89. InputStreamReader isr = null;
  90. BufferedReader br = null;
  91. FileOutputStream fos = null;
  92. PrintWriter pw = null;
  93. try {
  94. File file = new File(filePath);//文件路径(包括文件名称)
  95. //将文件读入输入流
  96. fis = new FileInputStream(file);
  97. isr = new InputStreamReader(fis);
  98. br = new BufferedReader(isr);
  99. StringBuffer buffer = new StringBuffer();
  100. //文件原有内容
  101. for(int i=0;(temp =br.readLine())!=null;i++){
  102. buffer.append(temp);
  103. // 行与行之间的分隔符 相当于“\n”
  104. buffer = buffer.append(System.getProperty("line.separator"));
  105. }
  106. buffer.append(filein);
  107. fos = new FileOutputStream(file);
  108. pw = new PrintWriter(fos);
  109. pw.write(buffer.toString().toCharArray());
  110. pw.flush();
  111. bool = true;
  112. } catch (Exception e) {
  113. // TODO: handle exception
  114. e.printStackTrace();
  115. }finally {
  116. //不要忘记关闭
  117. if (pw != null) {
  118. pw.close();
  119. }
  120. if (fos != null) {
  121. fos.close();
  122. }
  123. if (br != null) {
  124. br.close();
  125. }
  126. if (isr != null) {
  127. isr.close();
  128. }
  129. if (fis != null) {
  130. fis.close();
  131. }
  132. }
  133. return bool;
  134. }
  135. /**
  136. * 删除单个文件
  137. *
  138. * @param fileName
  139. * 要删除的文件的文件名
  140. * @return 单个文件删除成功返回true,否则返回false
  141. */
  142. public static boolean deleteFile(String fileName) {
  143. File file = new File(fileName);
  144. if (file.exists() && file.isFile()) {
  145. if (file.delete()) {
  146. return true;
  147. } else {
  148. return false;
  149. }
  150. } else {
  151. return false;
  152. }
  153. }
  154. /**
  155. * 根据路径删除指定的目录,无论存在与否
  156. *@param sPath 要删除的目录path
  157. *@return 删除成功返回 true,否则返回 false。
  158. */
  159. public static boolean deleteFolder(String sPath) {
  160. boolean flag = false;
  161. File file = new File(sPath);
  162. // 判断目录或文件是否存在
  163. if (!file.exists()) { // 不存在返回 false
  164. return flag;
  165. } else {
  166. // 判断是否为文件
  167. if (file.isFile()) { // 为文件时调用删除文件方法
  168. return deleteFile(sPath);
  169. } else { // 为目录时调用删除目录方法
  170. return deleteDirectory(sPath);
  171. }
  172. }
  173. }
  174. /**
  175. * 删除目录以及目录下的文件
  176. * @param dirPath 被删除目录的路径
  177. * @return 目录删除成功返回true,否则返回false
  178. */
  179. public static boolean deleteDirectory(String dirPath) {
  180. FileUtil.del(dirPath);
  181. return true;
  182. }
  183. //按行读文件
  184. public static String readFile(String path) {
  185. try {
  186. return FileUtil.readUtf8String(path);
  187. } catch (IORuntimeException e) {
  188. log.error("读取文件失败,文件不存在:{}", path);
  189. return null;
  190. }
  191. }
  192. public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
  193. FileUtil.copy(srcFileName,destFileName,overlay);
  194. return true;
  195. }
  196. // 复制文件
  197. public static void copyFile(File sourceFile,File targetFile){
  198. FileUtil.copy(sourceFile,targetFile,true);
  199. }
  200. public static void copyFolderAllFiles(String srcFolder, String destFolder, boolean overlay) {
  201. FileUtil.copyContent(new File(srcFolder),new File(destFolder),overlay);
  202. }
  203. // 复制文件夹
  204. public static void copyDirectiory(String sourceDir, String targetDir)
  205. throws IOException {
  206. if(!new File(sourceDir).exists()){
  207. return;
  208. }
  209. // 新建目标目录
  210. (new File(targetDir)).mkdirs();
  211. // 获取源文件夹当前下的文件或目录
  212. File[] file = (new File(sourceDir)).listFiles();
  213. for (int i = 0; i < file.length; i++) {
  214. if (file[i].isFile()) {
  215. // 源文件
  216. File sourceFile=file[i];
  217. // 目标文件
  218. File targetFile=new
  219. File(new File(targetDir).getAbsolutePath()
  220. +File.separator+file[i].getName());
  221. copyFile(sourceFile,targetFile);
  222. }
  223. if (file[i].isDirectory()) {
  224. // 准备复制的源文件夹
  225. String dir1=sourceDir + "/" + file[i].getName();
  226. // 准备复制的目标文件夹
  227. String dir2=targetDir + "/"+ file[i].getName();
  228. copyDirectiory(dir1, dir2);
  229. }
  230. }
  231. }
  232. /**
  233. * 从网络Url中下载文件
  234. *
  235. * @param urlStr
  236. * @param fileName
  237. * @param savePath
  238. * @return
  239. * @throws IOException
  240. */
  241. public static boolean downLoadFromUrl(String urlStr, String fileName, String savePath){
  242. HttpUtil.downloadFile(urlStr,savePath + File.separator + fileName);
  243. return true;
  244. }
  245. public static byte[] getBytesFromUrl(String urlStr){
  246. return HttpUtil.downloadBytes(urlStr);
  247. }
  248. public static String getStringFromUrl(String urlStr){
  249. return HttpUtil.downloadString(urlStr, StandardCharsets.UTF_8);
  250. }
  251. /**
  252. * 从输入流中获取字节数组
  253. *
  254. * @param inputStream
  255. * @return
  256. * @throws IOException
  257. */
  258. private static byte[] readInputStream(InputStream inputStream) throws IOException {
  259. byte[] buffer = new byte[1024];
  260. int len = 0;
  261. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  262. while ((len = inputStream.read(buffer)) != -1) {
  263. bos.write(buffer, 0, len);
  264. }
  265. bos.close();
  266. return bos.toByteArray();
  267. }
  268. public static void writeFile(String filePath,String str){
  269. if(!new File(filePath).getParentFile().exists()){
  270. new File(filePath).getParentFile().mkdirs();
  271. }
  272. FileUtil.writeString(str,filePath,StandardCharsets.UTF_8);
  273. }
  274. /**
  275. * 将byte数组写入文件
  276. *
  277. * @param path
  278. * @param fileName
  279. * @param content
  280. * @throws IOException
  281. */
  282. public static void writeFile(String path, String fileName, byte[] content){
  283. FileUtil.writeBytes(content,path + fileName);
  284. }
  285. /**
  286. * 向json文件写入参数,重复的覆盖,多的新增
  287. * @return
  288. */
  289. public static void writeJsonFile(String path, Map<String, Object> map){
  290. File file = new File(path);
  291. JSONObject json = new JSONObject();
  292. if(file.exists()){
  293. json = JSONObject.parseObject(FileUtil.readUtf8String(path));
  294. }
  295. json.putAll(map);
  296. FileUtils.writeFile(path,json.toJSONString());
  297. }
  298. public static void decompress(String srcPath, String dest){
  299. ZipUtil.unzip(srcPath,dest);
  300. }
  301. public static void zipFile(String zipFileName, String inputFileName){
  302. ZipUtil.zip(inputFileName,zipFileName);
  303. }
  304. //删除文件夹
  305. public static void delFolder(String folderPath) {
  306. FileUtil.del(folderPath);
  307. }
  308. //删除指定文件夹下的所有文件
  309. public static boolean delAllFile(String path) {
  310. FileUtil.del(path);
  311. return true;
  312. }
  313. public static List<String> readfileNamesForDirectory(String path, String except) {
  314. try {
  315. File file = new File(path);
  316. if (file.isDirectory()) {
  317. String[] fileNames = file.list();
  318. List<String> list = new ArrayList<String>();
  319. if (fileNames != null) {
  320. for (int i = 0; i < fileNames.length; ++i) {
  321. if (fileNames[i].toLowerCase().endsWith(except)) {
  322. list.add(fileNames[i]);
  323. }
  324. }
  325. }
  326. return list;
  327. }
  328. } catch (Exception e) {
  329. e.printStackTrace();
  330. }
  331. return null;
  332. }
  333. //递归获取文件中所有文件的路径
  334. public static List<String> readfilePath(String path, List<String> urlList) {
  335. try{
  336. File file = new File(path);
  337. if(file != null && file.isDirectory()) {
  338. File[] files = file.listFiles();
  339. if(files != null) {
  340. for(int i=0;i<files.length;++i) {
  341. if(files[i].isDirectory()){
  342. readfilePath(files[i].getAbsolutePath(), urlList);
  343. }else {
  344. urlList.add(files[i].getAbsolutePath());
  345. }
  346. }
  347. }
  348. return urlList;
  349. }
  350. }catch(Exception e){
  351. e.printStackTrace();
  352. }
  353. return urlList;
  354. }
  355. public static void saveImageToDisk(String accessToken, String mediaId, String picName, String picPath,InputStream inputStream){
  356. byte[] data = new byte[10240];
  357. int len = 0;
  358. FileOutputStream fileOutputStream = null;
  359. try {
  360. fileOutputStream = new FileOutputStream(picPath+picName+".amr");
  361. while ((len = inputStream.read(data)) != -1) {
  362. fileOutputStream.write(data, 0, len);
  363. }
  364. } catch (IOException e) {
  365. e.printStackTrace();
  366. } finally {
  367. if (inputStream != null) {
  368. try {
  369. inputStream.close();
  370. } catch (IOException e) {
  371. e.printStackTrace();
  372. }
  373. }
  374. if (fileOutputStream != null) {
  375. try {
  376. fileOutputStream.close();
  377. } catch (IOException e) {
  378. e.printStackTrace();
  379. }
  380. }
  381. }
  382. }
  383. //音频转换(To Mp3)
  384. public static void changeVoiceToMp3(String sourcePath,String targetPath){
  385. File source = new File(sourcePath);
  386. File target = new File(targetPath);
  387. if(target.exists())
  388. {
  389. target.delete();
  390. }
  391. AudioAttributes audio = new AudioAttributes();
  392. Encoder encoder = new Encoder();
  393. audio.setChannels(2);
  394. audio.setCodec("libmp3lame");
  395. EncodingAttributes attrs = new EncodingAttributes();
  396. attrs.setFormat("mp3");
  397. attrs.setAudioAttributes(audio);
  398. try {
  399. encoder.encode(source, target, attrs);
  400. } catch (IllegalArgumentException e) {
  401. e.printStackTrace();
  402. } catch (InputFormatException e) {
  403. e.printStackTrace();
  404. } catch (EncoderException e) {
  405. e.printStackTrace();
  406. }
  407. }
  408. /**
  409. * 获取指定视频的帧并保存为图片至指定目录
  410. * @param filePath 视频存放的地址
  411. * @param targerFilePath 截图存放的地址
  412. * @param targetFileName 截图保存的文件名称
  413. * @return
  414. * @throws Exception
  415. */
  416. public static boolean executeCodecs(String filePath, String targerFilePath, String targetFileName){
  417. try{
  418. FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(filePath);
  419. ff.start();
  420. String rotate =ff.getVideoMetadata("rotate");
  421. Frame f;
  422. int i = 0;
  423. while (i <1) {
  424. f =ff.grabImage();
  425. opencv_core.IplImage src = null;
  426. if(null !=rotate &&rotate.length() > 1) {
  427. OpenCVFrameConverter.ToIplImage converter =new OpenCVFrameConverter.ToIplImage();
  428. src =converter.convert(f);
  429. f =converter.convert(rotate(src, Integer.valueOf(rotate)));
  430. }
  431. doExecuteFrame(f,targerFilePath,targetFileName);
  432. i++;
  433. }
  434. ff.stop();
  435. return true;
  436. }catch (Exception e){
  437. e.printStackTrace();
  438. }
  439. return false;
  440. }
  441. /*
  442. * 旋转角度的
  443. */
  444. public static opencv_core.IplImage rotate(opencv_core.IplImage src, int angle) {
  445. opencv_core.IplImage img = opencv_core.IplImage.create(src.height(), src.width(), src.depth(), src.nChannels());
  446. opencv_core.cvTranspose(src, img);
  447. opencv_core.cvFlip(img, img, angle);
  448. return img;
  449. }
  450. public static void doExecuteFrame(Frame f, String targerFilePath, String targetFileName) {
  451. if (null ==f ||null ==f.image) {
  452. return;
  453. }
  454. Java2DFrameConverter converter =new Java2DFrameConverter();
  455. String imageMat ="jpg";
  456. String FileName =targerFilePath + File.separator +targetFileName +"." +imageMat;
  457. BufferedImage bi =converter.getBufferedImage(f);
  458. System.out.println("width:" + bi.getWidth());//打印宽、高
  459. System.out.println("height:" + bi.getHeight());
  460. File output =new File(FileName);
  461. try {
  462. ImageIO.write(bi,imageMat,output);
  463. }catch (IOException e) {
  464. e.printStackTrace();
  465. }
  466. }
  467. /**
  468. * 获取音频时长
  469. * @throws IOException
  470. */
  471. public static long getAudioPlayTime(File source){
  472. Encoder encoder = new Encoder();
  473. long ls = 0;
  474. try {
  475. MultimediaInfo m = encoder.getInfo(source);
  476. ls = m.getDuration();
  477. } catch (Exception e) {
  478. e.printStackTrace();
  479. }
  480. return ls;
  481. }
  482. public static void pngToJpg(String pngPath, String jpgPath){
  483. try {
  484. //1.读取本地png图片or读取url图片
  485. File input = new File(pngPath);
  486. BufferedImage bimg = ImageIO.read(input);//读取本地图片
  487. //BufferedImage bimg = ImageIO.read(new URL("http://img.alicdn.com/tfs/TB1kbMoUOLaK1RjSZFxXXamPFXa.png"));//读取url图片
  488. //2. 填充透明背景为白色
  489. BufferedImage res = new BufferedImage(bimg.getWidth(), bimg.getHeight(), BufferedImage.TYPE_INT_RGB);
  490. res.createGraphics().drawImage(bimg, 0, 0, Color.WHITE, null); //背景填充色设置为白色,也可以设置为其他颜色比如粉色Color.PINK
  491. //3. 保存成jpg到本地
  492. File output = new File(jpgPath);
  493. ImageIO.write(res, "jpg", output);
  494. } catch (Exception e) {
  495. e.printStackTrace();
  496. }
  497. }
  498. public static List<String> list(File file) throws Exception{
  499. List<String> keys = new ArrayList<>();
  500. //判断file是否是目录
  501. if(file.isDirectory()){
  502. File [] lists = file.listFiles();
  503. if(lists!=null){
  504. for(int i=0;i<lists.length;i++)
  505. {
  506. keys.addAll(list(lists[i]));//是目录就递归进入目录内再进行判断
  507. }
  508. }
  509. }else{
  510. keys.add(file.getAbsolutePath());
  511. }
  512. return keys;
  513. }
  514. /**
  515. *
  516. * @param content base64内容
  517. * @param path 输出文件路径,需要后缀名
  518. * @return
  519. */
  520. public static boolean base64ToFileWriter(String content, String path) {
  521. if (content == null) {
  522. return false;
  523. }
  524. BASE64Decoder decoder = new BASE64Decoder();
  525. try {
  526. // decoder
  527. byte[] b = decoder.decodeBuffer(content);
  528. // processing data
  529. for (int i = 0; i < b.length; ++i) {
  530. if (b[i] < 0) {
  531. b[i] += 256;
  532. }
  533. }
  534. FileUtil.writeBytes(b,path);
  535. return true;
  536. } catch (Exception e) {
  537. return false;
  538. }
  539. }
  540. /**
  541. * 已移除,请在项目中自行实现
  542. */
  543. // public static String getResource(){
  544. // String path = "";
  545. // try {
  546. // path = ResourceUtils.getURL("classpath:").getPath();
  547. // path = URLDecoder.decode(path,"utf-8");
  548. // } catch (Exception e) {
  549. // }
  550. // return path;
  551. // }
  552. /**
  553. * 判断文件大小处于限制内
  554. *
  555. * @param fileLen 文件长度
  556. * @param fileSize 限制大小
  557. * @param fileUnit 限制的单位(B,K,M,G)
  558. * @return
  559. */
  560. public static boolean checkFileSizeIsLimit(Long fileLen, double fileSize, String fileUnit) {
  561. // long len = file.length();
  562. double fileSizeCom = 0;
  563. if ("B".equals(fileUnit.toUpperCase())) {
  564. fileSizeCom = (double) fileLen;
  565. } else if ("K".equals(fileUnit.toUpperCase())) {
  566. fileSizeCom = (double) fileLen / 1024;
  567. } else if ("M".equals(fileUnit.toUpperCase())) {
  568. fileSizeCom = (double) fileLen / (1024*1024);
  569. } else if ("G".equals(fileUnit.toUpperCase())) {
  570. fileSizeCom = (double) fileLen / (1024*1024*1024);
  571. }
  572. if (fileSizeCom > fileSize) {
  573. return false;
  574. }
  575. return true;
  576. }
  577. private boolean checkFile(String fileName) {
  578. //设置允许上传文件类型
  579. String suffixList = ".jpg,.gif,.png,.ico,.bmp,.jpeg,.zip,.zp,.rar,.mp3,.mp4,.avi,.mov";
  580. // 获取文件后缀
  581. String suffix = fileName.substring(fileName.lastIndexOf(".")
  582. + 1, fileName.length());
  583. if (suffixList.contains(suffix.trim().toLowerCase())) {
  584. System.out.println("无非法参数可以放行!!!");
  585. log.info("无非法参数可以放行!!!");
  586. return true;
  587. }
  588. log.info("存在非法参数不能放行!请核对上传文件格式,重新刷新页面再次上传!");
  589. return false;
  590. }
  591. /**
  592. * 删除文件
  593. *
  594. * @param filePathAndName
  595. * String 文件路径及名称 如c:/fqf.txt
  596. * @return boolean
  597. */
  598. public static void delFile(String filePathAndName) {
  599. FileUtil.del(filePathAndName);
  600. }
  601. /**
  602. * 读取到字节数组0
  603. *
  604. * @param filePath //路径
  605. * @throws IOException
  606. */
  607. public static byte[] getContent(String filePath) throws IOException {
  608. File file = new File(filePath);
  609. long fileSize = file.length();
  610. if (fileSize > Integer.MAX_VALUE) {
  611. System.out.println("file too big...");
  612. return null;
  613. }
  614. FileInputStream fi = new FileInputStream(file);
  615. byte[] buffer = new byte[(int) fileSize];
  616. int offset = 0;
  617. int numRead = 0;
  618. while (offset < buffer.length
  619. && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
  620. offset += numRead;
  621. }
  622. // 确保所有数据均被读取
  623. if (offset != buffer.length) {
  624. throw new IOException("Could not completely read file "
  625. + file.getName());
  626. }
  627. fi.close();
  628. return buffer;
  629. }
  630. /**
  631. * 读取到字节数组1
  632. *
  633. * @param filePath
  634. * @return
  635. * @throws IOException
  636. */
  637. public static byte[] toByteArray(String filePath) throws IOException {
  638. File f = new File(filePath);
  639. if (!f.exists()) {
  640. throw new FileNotFoundException(filePath);
  641. }
  642. ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
  643. BufferedInputStream in = null;
  644. try {
  645. in = new BufferedInputStream(new FileInputStream(f));
  646. int buf_size = 1024;
  647. byte[] buffer = new byte[buf_size];
  648. int len = 0;
  649. while (-1 != (len = in.read(buffer, 0, buf_size))) {
  650. bos.write(buffer, 0, len);
  651. }
  652. return bos.toByteArray();
  653. } catch (IOException e) {
  654. e.printStackTrace();
  655. throw e;
  656. } finally {
  657. try {
  658. in.close();
  659. } catch (IOException e) {
  660. e.printStackTrace();
  661. }
  662. bos.close();
  663. }
  664. }
  665. /**
  666. * 读取到字节数组2
  667. *
  668. * @param filePath
  669. * @return
  670. * @throws IOException
  671. */
  672. public static byte[] toByteArray2(String filePath) throws IOException {
  673. File f = new File(filePath);
  674. if (!f.exists()) {
  675. throw new FileNotFoundException(filePath);
  676. }
  677. FileChannel channel = null;
  678. FileInputStream fs = null;
  679. try {
  680. fs = new FileInputStream(f);
  681. channel = fs.getChannel();
  682. ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
  683. while ((channel.read(byteBuffer)) > 0) {
  684. // do nothing
  685. // System.out.println("reading");
  686. }
  687. return byteBuffer.array();
  688. } catch (IOException e) {
  689. e.printStackTrace();
  690. throw e;
  691. } finally {
  692. try {
  693. channel.close();
  694. } catch (IOException e) {
  695. e.printStackTrace();
  696. }
  697. try {
  698. fs.close();
  699. } catch (IOException e) {
  700. e.printStackTrace();
  701. }
  702. }
  703. }
  704. /**
  705. * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
  706. *
  707. * @param filePath
  708. * @return
  709. * @throws IOException
  710. */
  711. public static byte[] toByteArray3(String filePath) throws IOException {
  712. FileChannel fc = null;
  713. RandomAccessFile rf = null;
  714. try {
  715. rf = new RandomAccessFile(filePath, "r");
  716. fc = rf.getChannel();
  717. MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0,
  718. fc.size()).load();
  719. //System.out.println(byteBuffer.isLoaded());
  720. byte[] result = new byte[(int) fc.size()];
  721. if (byteBuffer.remaining() > 0) {
  722. // System.out.println("remain");
  723. byteBuffer.get(result, 0, byteBuffer.remaining());
  724. }
  725. return result;
  726. } catch (IOException e) {
  727. e.printStackTrace();
  728. throw e;
  729. } finally {
  730. try {
  731. rf.close();
  732. fc.close();
  733. } catch (IOException e) {
  734. e.printStackTrace();
  735. }
  736. }
  737. }
  738. public static File[] sort(File[] s) {
  739. return Arrays.stream(s).sorted(Comparator.comparingInt(o -> Integer.parseInt(FileUtil.mainName(o)))).collect(Collectors.toList()).toArray(new File[]{});
  740. }
  741. /**
  742. * 获取目录下所有文件
  743. * @param directory
  744. */
  745. public static List<String> getFileList(String directory) {
  746. File f = new File(directory);
  747. File[] files = f.listFiles();
  748. if(files == null || files.length == 0){
  749. return null;
  750. }
  751. List<String> list = new ArrayList<>();
  752. for (int i = 0; i < files.length; i++) {
  753. if (files[i].isFile()) {
  754. list.add(files[i].getAbsolutePath());
  755. } else {
  756. System.out.println("目录:" + files[i]);
  757. List<String> fileList = getFileList(files[i].getAbsolutePath());
  758. if(CollUtil.isEmpty(fileList)){
  759. continue;
  760. }
  761. list.addAll(fileList);
  762. }
  763. }
  764. return list;
  765. }
  766. /**
  767. * <p>
  768. zip包解压缩
  769. * </p>
  770. * @author dengsixing
  771. * @date 2022/2/16
  772. * @param inputFile 解压文件路径
  773. * @param destDirPath 解压目标目录
  774. **/
  775. public static void unZip(String inputFile,String destDirPath){
  776. ZipUtil.unzip(inputFile,destDirPath);
  777. }
  778. /**
  779. * <p>
  780. 打包
  781. * </p>
  782. * @author dengsixing
  783. * @date 2022/2/16
  784. * @param inputFile
  785. * @param outputFile
  786. * @param withDir
  787. **/
  788. public static void zip(String inputFile, String outputFile, boolean withDir) throws Exception {
  789. try (
  790. //创建zip输出流
  791. java.util.zip.ZipOutputStream out = new java.util.zip.ZipOutputStream(new FileOutputStream(outputFile));
  792. //创建缓冲输出流
  793. BufferedOutputStream bos = new BufferedOutputStream(out);
  794. ) {
  795. File input = new File(inputFile);
  796. compress(out, bos, input, null, withDir);
  797. }
  798. }
  799. /**
  800. * @param name 压缩文件名,可以写为null保持默认
  801. */
  802. //递归压缩
  803. public static void compress(java.util.zip.ZipOutputStream out, BufferedOutputStream bos, File input, String name, boolean withDir) throws IOException {
  804. if (name == null) {
  805. name = input.getName();
  806. }
  807. //如果路径为目录(文件夹)
  808. if (input.isDirectory()) {
  809. //取出文件夹中的文件(或子文件夹)
  810. File[] flist = input.listFiles();
  811. if (flist.length == 0) {//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入
  812. if (withDir) {
  813. out.putNextEntry(new java.util.zip.ZipEntry(name + "/"));
  814. }
  815. } else {//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
  816. for (int i = 0; i < flist.length; i++) {
  817. if (withDir) {
  818. compress(out, bos, flist[i], name + "/" + flist[i].getName(), withDir);
  819. } else {
  820. compress(out, bos, flist[i], flist[i].getName(), withDir);
  821. }
  822. }
  823. }
  824. } else {//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
  825. out.putNextEntry(new java.util.zip.ZipEntry(name));
  826. FileInputStream fos = new FileInputStream(input);
  827. BufferedInputStream bis = new BufferedInputStream(fos);
  828. int len;
  829. //将源文件写入到zip文件中
  830. byte[] buf = new byte[1024];
  831. while ((len = bis.read(buf)) != -1) {
  832. bos.write(buf, 0, len);
  833. }
  834. bis.close();
  835. fos.close();
  836. }
  837. }
  838. public static JSONObject readJson(String filePath) throws IOException {
  839. try {
  840. String content = FileUtil.readUtf8String(filePath);
  841. JSONObject jsonObj = JSON.parseObject(content);
  842. return jsonObj;
  843. } catch (Exception e) {
  844. log.error("读取json失败,filePath=" + filePath, e);
  845. return null;
  846. }
  847. }
  848. /**
  849. * utf-8格式读取文件,若文件不存在或者读取文件异常,返回null
  850. * @param path
  851. * @return
  852. */
  853. public static String readUtf8String(String path){
  854. try {
  855. return FileUtil.readUtf8String(path);
  856. }catch (Exception e){
  857. log.warn("读取文件失败,path:{}", path);
  858. }
  859. return null;
  860. }
  861. }