FileUtils.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. package com.fdkankan.util;
  2. import com.alibaba.fastjson.JSONObject;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.util.ResourceUtils;
  5. import sun.misc.BASE64Decoder;
  6. import java.io.*;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.net.URLDecoder;
  10. import java.util.*;
  11. @Slf4j
  12. public class FileUtils {
  13. //文件路径+名称
  14. private static String fileNameTemp;
  15. public static void uploadImg(String path, String base64Data)
  16. throws Exception {
  17. byte[] bt = null;
  18. try {
  19. BASE64Decoder decoder = new BASE64Decoder();
  20. if (base64Data.startsWith("data:image/png;base64,")) {
  21. bt = decoder.decodeBuffer(base64Data.replace("data:image/png;base64,", ""));
  22. } else if (base64Data.startsWith("data:image/jpeg;base64,")) {
  23. bt = decoder.decodeBuffer(base64Data.replace("data:image/jpeg;base64,", ""));
  24. } else if (base64Data.startsWith("data:image/bmp;base64,")) {
  25. bt = decoder.decodeBuffer(base64Data.replace("data:image/bmp;base64,", ""));
  26. } else {
  27. return;
  28. }
  29. writeBinary(bt, path);
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. private static void writeBinary(byte[] buf, String filePath) throws Exception {
  35. File fout = new File(filePath);
  36. if (!fout.getParentFile().exists()) {
  37. fout.getParentFile().mkdirs();
  38. }
  39. FileOutputStream fos = new FileOutputStream(fout);
  40. ByteArrayInputStream stream = new ByteArrayInputStream(buf);
  41. BufferedOutputStream bos = new BufferedOutputStream(fos);//设置输出路径
  42. BufferedInputStream bis = new BufferedInputStream(stream);
  43. int b = -1;
  44. while ((b = bis.read()) != -1) {
  45. bos.write(b);
  46. }
  47. bis.close();
  48. bos.close();
  49. }
  50. public static boolean createDir(String destDirName) {
  51. File dir = new File(destDirName);
  52. if (dir.exists()) {
  53. System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
  54. return false;
  55. }
  56. if (!destDirName.endsWith(File.separator)) {
  57. destDirName = destDirName + File.separator;
  58. }
  59. //创建目录
  60. if (dir.mkdirs()) {
  61. System.out.println("创建目录" + destDirName + "成功!");
  62. return true;
  63. } else {
  64. System.out.println("创建目录" + destDirName + "失败!");
  65. return false;
  66. }
  67. }
  68. /**
  69. * 创建文件
  70. * @param fileName 文件名称
  71. * @param fileContent 文件内容
  72. * @return 是否创建成功,成功则返回true
  73. */
  74. public static boolean createFile(String path, String fileName,String fileContent){
  75. Boolean bool = false;
  76. fileNameTemp = path+fileName+".json";//文件路径+名称+文件类型
  77. File file = new File(fileNameTemp);
  78. try {
  79. File folder = new File(path);
  80. if (!folder.exists()){
  81. folder.mkdirs();
  82. }
  83. //如果文件不存在,则创建新的文件
  84. if(!file.exists()){
  85. file.createNewFile();
  86. bool = true;
  87. System.out.println("success create file,the file is "+ fileNameTemp);
  88. //创建文件成功后,写入内容到文件里
  89. writeFileContent(fileNameTemp, fileContent);
  90. }
  91. } catch (Exception e) {
  92. e.printStackTrace();
  93. }
  94. return bool;
  95. }
  96. /**
  97. * 向文件中写入内容
  98. * @param filePath 文件路径与名称
  99. * @param newstr 写入的内容
  100. * @return
  101. * @throws IOException
  102. */
  103. public static boolean writeFileContent(String filePath, String newstr) throws IOException{
  104. Boolean bool = false;
  105. String filein = newstr+"\r\n";//新写入的行,换行
  106. String temp = "";
  107. FileInputStream fis = null;
  108. InputStreamReader isr = null;
  109. BufferedReader br = null;
  110. FileOutputStream fos = null;
  111. PrintWriter pw = null;
  112. try {
  113. File file = new File(filePath);//文件路径(包括文件名称)
  114. //将文件读入输入流
  115. fis = new FileInputStream(file);
  116. isr = new InputStreamReader(fis);
  117. br = new BufferedReader(isr);
  118. StringBuffer buffer = new StringBuffer();
  119. //文件原有内容
  120. for(int i=0;(temp =br.readLine())!=null;i++){
  121. buffer.append(temp);
  122. // 行与行之间的分隔符 相当于“\n”
  123. buffer = buffer.append(System.getProperty("line.separator"));
  124. }
  125. buffer.append(filein);
  126. fos = new FileOutputStream(file);
  127. pw = new PrintWriter(fos);
  128. pw.write(buffer.toString().toCharArray());
  129. pw.flush();
  130. bool = true;
  131. } catch (Exception e) {
  132. // TODO: handle exception
  133. e.printStackTrace();
  134. }finally {
  135. //不要忘记关闭
  136. if (pw != null) {
  137. pw.close();
  138. }
  139. if (fos != null) {
  140. fos.close();
  141. }
  142. if (br != null) {
  143. br.close();
  144. }
  145. if (isr != null) {
  146. isr.close();
  147. }
  148. if (fis != null) {
  149. fis.close();
  150. }
  151. }
  152. return bool;
  153. }
  154. /**
  155. * 删除单个文件
  156. *
  157. * @param fileName
  158. * 要删除的文件的文件名
  159. * @return 单个文件删除成功返回true,否则返回false
  160. */
  161. public static boolean deleteFile(String fileName) {
  162. File file = new File(fileName);
  163. if (file.exists() && file.isFile()) {
  164. if (file.delete()) {
  165. return true;
  166. } else {
  167. return false;
  168. }
  169. } else {
  170. return false;
  171. }
  172. }
  173. /**
  174. * 根据路径删除指定的目录,无论存在与否
  175. *@param sPath 要删除的目录path
  176. *@return 删除成功返回 true,否则返回 false。
  177. */
  178. public static boolean deleteFolder(String sPath) {
  179. boolean flag = false;
  180. File file = new File(sPath);
  181. // 判断目录或文件是否存在
  182. if (!file.exists()) { // 不存在返回 false
  183. return flag;
  184. } else {
  185. // 判断是否为文件
  186. if (file.isFile()) { // 为文件时调用删除文件方法
  187. return deleteFile(sPath);
  188. } else { // 为目录时调用删除目录方法
  189. return deleteDirectory(sPath);
  190. }
  191. }
  192. }
  193. /**
  194. * 删除目录以及目录下的文件
  195. * @param sPath 被删除目录的路径
  196. * @return 目录删除成功返回true,否则返回false
  197. */
  198. public static boolean deleteDirectory(String sPath) {
  199. //如果sPath不以文件分隔符结尾,自动添加文件分隔符
  200. if (!sPath.endsWith(File.separator)) {
  201. sPath = sPath + File.separator;
  202. }
  203. File dirFile = new File(sPath);
  204. //如果dir对应的文件不存在,或者不是一个目录,则退出
  205. if (!dirFile.exists() || !dirFile.isDirectory()) {
  206. return false;
  207. }
  208. boolean flag = true;
  209. //删除文件夹下的所有文件(包括子目录)
  210. File[] files = dirFile.listFiles();
  211. for (int i = 0; i < files.length; i++) {
  212. //删除子文件
  213. if (files[i].isFile()) {
  214. flag = deleteFile(files[i].getAbsolutePath());
  215. if (!flag) break;
  216. } //删除子目录
  217. else {
  218. flag = deleteDirectory(files[i].getAbsolutePath());
  219. if (!flag) break;
  220. }
  221. }
  222. if (!flag) return false;
  223. //删除当前目录
  224. if (dirFile.delete()) {
  225. return true;
  226. } else {
  227. return false;
  228. }
  229. }
  230. //按行读文件
  231. public static String readFile(String path) throws Exception {
  232. File f = new File(path);
  233. if (!f.exists()) {
  234. return null;
  235. }
  236. ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
  237. BufferedInputStream in = null;
  238. try {
  239. in = new BufferedInputStream(new FileInputStream(f));
  240. int buf_size = 1024;
  241. byte[] buffer = new byte[buf_size];
  242. int len = 0;
  243. while (-1 != (len = in.read(buffer, 0, buf_size))) {
  244. bos.write(buffer, 0, len);
  245. }
  246. return bos.toString();
  247. } catch (IOException e) {
  248. e.printStackTrace();
  249. throw e;
  250. } finally {
  251. try {
  252. in.close();
  253. } catch (IOException e) {
  254. e.printStackTrace();
  255. }
  256. bos.close();
  257. }
  258. }
  259. public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
  260. File srcFile = new File(srcFileName);
  261. // 判断源文件是否存在
  262. if (!srcFile.exists()) {
  263. return false;
  264. } else if (!srcFile.isFile()) {
  265. return false;
  266. }
  267. // 判断目标文件是否存在
  268. File destFile = new File(destFileName);
  269. if (destFile.exists()) {
  270. // 如果目标文件存在并允许覆盖
  271. if (overlay) {
  272. // 删除已经存在的目标文件,无论目标文件是目录还是单个文件
  273. new File(destFileName).delete();
  274. }
  275. } else {
  276. // 如果目标文件所在目录不存在,则创建目录
  277. if (!destFile.getParentFile().exists()) {
  278. // 目标文件所在目录不存在
  279. if (!destFile.getParentFile().mkdirs()) {
  280. // 复制文件失败:创建目标文件所在目录失败
  281. return false;
  282. }
  283. }
  284. }
  285. // 复制文件
  286. int byteread = 0; // 读取的字节数
  287. InputStream in = null;
  288. OutputStream out = null;
  289. try {
  290. in = new FileInputStream(srcFile);
  291. out = new FileOutputStream(destFile);
  292. byte[] buffer = new byte[1024];
  293. while ((byteread = in.read(buffer)) != -1) {
  294. out.write(buffer, 0, byteread);
  295. }
  296. return true;
  297. } catch (IOException e) {
  298. return false;
  299. } finally {
  300. try {
  301. if (out != null)
  302. out.close();
  303. if (in != null)
  304. in.close();
  305. } catch (IOException e) {
  306. e.printStackTrace();
  307. }
  308. }
  309. }
  310. /**
  311. * 从网络Url中下载文件
  312. *
  313. * @param urlStr
  314. * @param fileName
  315. * @param savePath
  316. * @return
  317. * @throws IOException
  318. */
  319. public static boolean downLoadFromUrl(String urlStr, String fileName, String savePath){
  320. FileOutputStream fos = null;
  321. InputStream inputStream = null;
  322. try {
  323. URL url = new URL(urlStr);
  324. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  325. // 设置超时间为3秒
  326. conn.setConnectTimeout(3 * 1000);
  327. // 防止屏蔽程序抓取而返回403错误
  328. conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  329. // 得到输入流
  330. inputStream = conn.getInputStream();
  331. // 获取自己数组
  332. byte[] getData = readInputStream(inputStream);
  333. // 文件保存位置
  334. File saveDir = new File(savePath);
  335. if (!saveDir.exists()) {
  336. saveDir.mkdirs();
  337. }
  338. String filePath = saveDir + File.separator + fileName;
  339. String filePathFolder = filePath.substring(0, filePath.lastIndexOf("/") + 1);
  340. FileUtils.createDir(filePathFolder);
  341. File file = new File(filePath);
  342. fos = new FileOutputStream(file);
  343. fos.write(getData);
  344. if (fos != null) {
  345. fos.close();
  346. }
  347. if (inputStream != null) {
  348. inputStream.close();
  349. }
  350. System.out.println("info:" + url + " download success");
  351. } catch(FileNotFoundException e){
  352. return false;
  353. } catch (IOException e) {
  354. return false;
  355. }finally {
  356. if (fos != null) {
  357. try {
  358. fos.close();
  359. } catch (IOException e) {
  360. e.printStackTrace();
  361. }
  362. }
  363. if (inputStream != null) {
  364. try {
  365. inputStream.close();
  366. } catch (IOException e) {
  367. e.printStackTrace();
  368. }
  369. }
  370. }
  371. return true;
  372. }
  373. /**
  374. * 从输入流中获取字节数组
  375. *
  376. * @param inputStream
  377. * @return
  378. * @throws IOException
  379. */
  380. private static byte[] readInputStream(InputStream inputStream) throws IOException {
  381. byte[] buffer = new byte[1024];
  382. int len = 0;
  383. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  384. while ((len = inputStream.read(buffer)) != -1) {
  385. bos.write(buffer, 0, len);
  386. }
  387. bos.close();
  388. return bos.toByteArray();
  389. }
  390. public static void writeFile(String filePath,String str) throws IOException {
  391. File fout = new File(filePath);
  392. if(!fout.getParentFile().exists()){
  393. fout.getParentFile().mkdirs();
  394. }
  395. if(!fout.exists()){
  396. fout.createNewFile();
  397. }
  398. FileOutputStream fos = new FileOutputStream(fout);
  399. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
  400. bw.write(str);
  401. bw.close();
  402. }
  403. /**
  404. * 将byte数组写入文件
  405. *
  406. * @param path
  407. * @param fileName
  408. * @param content
  409. * @throws IOException
  410. */
  411. public static void writeFile(String path, String fileName, byte[] content)
  412. throws IOException {
  413. try {
  414. File f = new File(path);
  415. if (!f.exists()) {
  416. f.mkdirs();
  417. }
  418. FileOutputStream fos = new FileOutputStream(path + fileName);
  419. fos.write(content);
  420. fos.close();
  421. } catch (IOException e) {
  422. throw new RuntimeException(e);
  423. }
  424. }
  425. /**
  426. * 向json文件写入参数,重复的覆盖,多的新增
  427. * @return
  428. */
  429. public static void writeJsonFile(String path, Map<String, Object> map) throws Exception{
  430. String str = readFile(path);
  431. JSONObject json = new JSONObject();
  432. if(str!=null){
  433. json = JSONObject.parseObject(str);
  434. }
  435. else{
  436. File file = new File(path);
  437. if(!file.getParentFile().exists())
  438. {
  439. file.getParentFile().mkdirs();
  440. }
  441. if(!file.exists())
  442. {
  443. file.createNewFile();
  444. }
  445. }
  446. Iterator entries = map.entrySet().iterator();
  447. while (entries.hasNext()) {
  448. Map.Entry entry = (Map.Entry) entries.next();
  449. json.put(String.valueOf(entry.getKey()), entry.getValue());
  450. }
  451. writeFile(path, json.toString());
  452. }
  453. //删除文件夹
  454. public static void delFolder(String folderPath) {
  455. try {
  456. delAllFile(folderPath); //删除完里面所有内容
  457. String filePath = folderPath;
  458. filePath = filePath.toString();
  459. File myFilePath = new File(filePath);
  460. myFilePath.delete(); //删除空文件夹
  461. } catch (Exception e) {
  462. e.printStackTrace();
  463. }
  464. }
  465. //删除指定文件夹下的所有文件
  466. public static boolean delAllFile(String path) {
  467. boolean flag = false;
  468. File file = new File(path);
  469. if (!file.exists()) {
  470. return flag;
  471. }
  472. if (!file.isDirectory()) {
  473. return flag;
  474. }
  475. String[] tempList = file.list();
  476. File temp = null;
  477. if(tempList!=null)
  478. {
  479. for (int i = 0; i < tempList.length; i++) {
  480. if (path.endsWith(File.separator)) {
  481. temp = new File(path + tempList[i]);
  482. } else {
  483. temp = new File(path + File.separator + tempList[i]);
  484. }
  485. if (temp.isFile()) {
  486. temp.delete();
  487. }
  488. if (temp.isDirectory()) {
  489. delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
  490. delFolder(path + "/" + tempList[i]);//再删除空文件夹
  491. flag = true;
  492. }
  493. }
  494. }
  495. //再删除当前空文件夹
  496. file.delete();
  497. return flag;
  498. }
  499. public static List<String> readfileNamesForDirectory(String path, String except)
  500. {
  501. try{
  502. File file = new File(path);
  503. if(file.isDirectory())
  504. {
  505. String[] fileNames = file.list();
  506. List<String> list = new ArrayList<String>();
  507. if(fileNames!=null)
  508. {
  509. for(int i=0;i<fileNames.length;++i)
  510. {
  511. if(fileNames[i].toLowerCase().endsWith(except) )
  512. {
  513. list.add(fileNames[i]);
  514. }
  515. }
  516. }
  517. return list;
  518. }
  519. }catch(Exception e){
  520. e.printStackTrace();
  521. }
  522. return null;
  523. }
  524. //递归获取文件中所有文件的路径
  525. public static List<String> readfilePath(String path, List<String> urlList) {
  526. try{
  527. File file = new File(path);
  528. if(file != null && file.isDirectory()) {
  529. File[] files = file.listFiles();
  530. if(files != null) {
  531. for(int i=0;i<files.length;++i) {
  532. if(files[i].isDirectory()){
  533. readfilePath(files[i].getAbsolutePath(), urlList);
  534. }else {
  535. urlList.add(files[i].getAbsolutePath());
  536. }
  537. }
  538. }
  539. return urlList;
  540. }
  541. }catch(Exception e){
  542. e.printStackTrace();
  543. }
  544. return urlList;
  545. }
  546. public static void saveImageToDisk(String accessToken, String mediaId, String picName, String picPath,InputStream inputStream)
  547. throws Exception {
  548. byte[] data = new byte[10240];
  549. int len = 0;
  550. FileOutputStream fileOutputStream = null;
  551. try {
  552. fileOutputStream = new FileOutputStream(picPath+picName+".amr");
  553. while ((len = inputStream.read(data)) != -1) {
  554. fileOutputStream.write(data, 0, len);
  555. }
  556. } catch (IOException e) {
  557. e.printStackTrace();
  558. } finally {
  559. if (inputStream != null) {
  560. try {
  561. inputStream.close();
  562. } catch (IOException e) {
  563. e.printStackTrace();
  564. }
  565. }
  566. if (fileOutputStream != null) {
  567. try {
  568. fileOutputStream.close();
  569. } catch (IOException e) {
  570. e.printStackTrace();
  571. }
  572. }
  573. }
  574. }
  575. /**
  576. *
  577. * @param content base64内容
  578. * @param path 输出文件路径,需要后缀名
  579. * @return
  580. */
  581. public static boolean base64ToFileWriter(String content, String path) {
  582. if (content == null) {
  583. return false;
  584. }
  585. BASE64Decoder decoder = new BASE64Decoder();
  586. try {
  587. // decoder
  588. byte[] b = decoder.decodeBuffer(content);
  589. // processing data
  590. for (int i = 0; i < b.length; ++i) {
  591. if (b[i] < 0) {
  592. b[i] += 256;
  593. }
  594. }
  595. OutputStream out = new FileOutputStream(path);
  596. out.write(b);
  597. out.flush();
  598. out.close();
  599. return true;
  600. } catch (Exception e) {
  601. return false;
  602. }
  603. }
  604. /**
  605. * 获取类路径(classes路径)
  606. */
  607. public static String getResource(){
  608. String path = "";
  609. try {
  610. path = ResourceUtils.getURL("classpath:").getPath();
  611. path = URLDecoder.decode(path,"utf-8");
  612. } catch (Exception e) {
  613. }
  614. return path;
  615. }
  616. /**
  617. * 判断文件大小处于限制内
  618. *
  619. * @param fileLen 文件长度
  620. * @param fileSize 限制大小
  621. * @param fileUnit 限制的单位(B,K,M,G)
  622. * @return
  623. */
  624. public static boolean checkFileSizeIsLimit(Long fileLen, double fileSize, String fileUnit) {
  625. // long len = file.length();
  626. double fileSizeCom = 0;
  627. if ("B".equals(fileUnit.toUpperCase())) {
  628. fileSizeCom = (double) fileLen;
  629. } else if ("K".equals(fileUnit.toUpperCase())) {
  630. fileSizeCom = (double) fileLen / 1024;
  631. } else if ("M".equals(fileUnit.toUpperCase())) {
  632. fileSizeCom = (double) fileLen / (1024*1024);
  633. } else if ("G".equals(fileUnit.toUpperCase())) {
  634. fileSizeCom = (double) fileLen / (1024*1024*1024);
  635. }
  636. if (fileSizeCom > fileSize) {
  637. return false;
  638. }
  639. return true;
  640. }
  641. public static void main(String[] args) {
  642. // File f = new File("F:\\桌面\\vr-t-2KZ4MQv");
  643. // for(File f1 : f.listFiles()){
  644. // f1.renameTo(new File(f1.getAbsolutePath().replace(".png", ".jpg")));
  645. // }
  646. System.out.println(System.currentTimeMillis());
  647. }
  648. }