FileUtils.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. package com.fdkanfang.common.util;
  2. import lombok.extern.log4j.Log4j2;
  3. import org.springframework.util.ResourceUtils;
  4. import javax.servlet.http.HttpServletResponse;
  5. import java.io.*;
  6. import java.net.URLDecoder;
  7. import java.net.URLEncoder;
  8. import java.nio.charset.Charset;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Base64;
  11. import java.util.Date;
  12. import java.util.Enumeration;
  13. import java.util.zip.ZipEntry;
  14. import java.util.zip.ZipFile;
  15. /**
  16. * Created by Owen on 2019/10/25 0025 14:20
  17. */
  18. @Log4j2
  19. public class FileUtils {
  20. /**
  21. * web 文件下载
  22. * @param response
  23. * @param path 源文件路径
  24. * @param path 源文件名
  25. * @return
  26. * @throws Exception
  27. */
  28. public static void fileDownload(HttpServletResponse response, String path) throws Exception {
  29. String fileName = path.substring(path.lastIndexOf(File.separator)+1);
  30. // 当文件名不是英文名的时候,最好使用url解码器去编码一下,
  31. fileName= URLEncoder.encode(fileName,"UTF-8");
  32. // 获取response的输出流,用来输出文件
  33. // ServletOutputStream out = response.getOutputStream();
  34. OutputStream out = response.getOutputStream();
  35. // 将响应的类型
  36. response.setContentType("APPLICATION/OCTET-STREAM");
  37. response.setHeader("Content-Disposition","attachment; filename="+fileName);
  38. // 以输入流的形式读取文件
  39. // log.info("zipPath: " + path);
  40. FileInputStream in = new FileInputStream(path);
  41. //可以自己 指定缓冲区的大小
  42. byte[] buffer = new byte[1024];
  43. int len = 0;
  44. while ((len = in.read(buffer)) != -1) {
  45. out.write(buffer, 0, len);
  46. out.flush();
  47. }
  48. //关闭输入输出流
  49. out.close();
  50. in.close();
  51. }
  52. /**
  53. * 获取类路径
  54. */
  55. public static String getResource(){
  56. String path = "";
  57. try {
  58. path = ResourceUtils.getURL("classpath:").getPath();
  59. path = URLDecoder.decode(path,"utf-8");
  60. log.info("classpath path :"+path);
  61. } catch (Exception e) {
  62. log.error(" classpath Error" + e.getMessage(), e);
  63. }
  64. return path;
  65. }
  66. /**
  67. * 创建文件夹
  68. * destDirName:文件夹名称
  69. */
  70. public static void createDir(String destDirName) {
  71. File dir = new File(destDirName);
  72. // 创建目录
  73. if (!dir.exists()) {
  74. dir.mkdirs();
  75. }
  76. }
  77. /**
  78. * 创建文件夹,如果存在,则先删除,再创建
  79. * destDirName:文件夹名称
  80. */
  81. public static void createDirIfExistThenDel(String destDirName) {
  82. File dir = new File(destDirName);
  83. // 创建目录
  84. if (dir.exists() && dir.isDirectory()) {
  85. //存在,则先删除,再创建
  86. deleteDirectory(destDirName);
  87. }
  88. createDir(destDirName);
  89. }
  90. /**
  91. * 大文件读写
  92. *
  93. * 1.先将文件中的内容读入到缓冲输入流中
  94. * 2.将输入流中的数据通过缓冲输出流写入到目标文件中
  95. * 3.关闭输入流和输出流
  96. *
  97. * in: 输入流
  98. * path: 保持位置
  99. */
  100. public static int downloanAndGetResolutionRate(InputStream in, String fileFullPath, boolean needCheckResolutin) throws IOException {
  101. // 输入缓冲流
  102. File file = new File(fileFullPath);
  103. if(file.exists()){
  104. deleteFile(fileFullPath);
  105. file = new File(fileFullPath);
  106. }
  107. BufferedInputStream inputBuff = new BufferedInputStream(in);
  108. // 输出缓冲流
  109. BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
  110. int len = 0;
  111. byte[] buffer = new byte[1024];
  112. while ((len = inputBuff.read(buffer)) != -1) {
  113. stream.write(buffer, 0, len);
  114. }
  115. stream.flush();
  116. stream.close();
  117. inputBuff.close();
  118. int totalResolutinRate = -1;
  119. if(needCheckResolutin){
  120. SimpleImageInfo simpleImageInfo = new SimpleImageInfo(file);
  121. if(null != simpleImageInfo){
  122. if(simpleImageInfo.getWidth() < simpleImageInfo.getHeight()){
  123. totalResolutinRate = simpleImageInfo.getHeight();
  124. }else{
  125. totalResolutinRate = simpleImageInfo.getWidth();
  126. }
  127. }
  128. }
  129. return totalResolutinRate;
  130. }
  131. /**
  132. * 删除单个文件
  133. *
  134. * @param fileName 要删除的文件的文件名
  135. * @return 单个文件删除成功返回true,否则返回false
  136. */
  137. public static boolean deleteFile(String fileName) {
  138. File file = new File(fileName);
  139. if (file.exists() && file.isFile()) {
  140. if (file.delete()) {
  141. return true;
  142. } else {
  143. return false;
  144. }
  145. } else {
  146. return false;
  147. }
  148. }
  149. /**
  150. *
  151. * @param content base64内容
  152. * @param path 输出文件路径,需要后缀名
  153. * @return
  154. */
  155. public static boolean base64ToFileWriter(String content, String path) {
  156. if (content == null) {
  157. return false;
  158. }
  159. try {
  160. byte[] b = Base64.getDecoder().decode(content);
  161. // processing data
  162. for (int i = 0; i < b.length; ++i) {
  163. if (b[i] < 0) {
  164. b[i] += 256;
  165. }
  166. }
  167. OutputStream out = new FileOutputStream(path);
  168. out.write(b);
  169. out.flush();
  170. out.close();
  171. return true;
  172. } catch (Exception e) {
  173. return false;
  174. }
  175. }
  176. /**
  177. * 读取文件方法
  178. * @param Path 文件路径
  179. * @return 返回内容
  180. */
  181. public static String readFile(String Path){
  182. BufferedReader reader = null;
  183. String laststr = "";
  184. try{
  185. FileInputStream fileInputStream = new FileInputStream(Path);
  186. InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
  187. reader = new BufferedReader(inputStreamReader);
  188. String tempString = null;
  189. while((tempString = reader.readLine()) != null){
  190. laststr += tempString;
  191. }
  192. reader.close();
  193. }catch(IOException e){
  194. e.printStackTrace();
  195. }finally{
  196. if(reader != null){
  197. try {
  198. reader.close();
  199. } catch (IOException e) {
  200. e.printStackTrace();
  201. }
  202. }
  203. }
  204. return laststr;
  205. }
  206. /**
  207. * 生成文件
  208. * @param content 内容
  209. * @param path 生成路径
  210. * @throws IOException
  211. */
  212. public static void fileWriter(String content, String path) throws IOException {
  213. FileWriter writer = new FileWriter(path);
  214. writer.write(content);
  215. writer.flush();
  216. writer.close();
  217. }
  218. public static void writeFile(String filePath,String str) throws IOException {
  219. File fout = new File(filePath);
  220. if(!fout.getParentFile().exists()){
  221. fout.getParentFile().mkdirs();
  222. }
  223. if(!fout.exists()){
  224. fout.createNewFile();
  225. }
  226. FileOutputStream fos = new FileOutputStream(fout);
  227. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
  228. bw.write(str);
  229. bw.close();
  230. }
  231. // 获取时间戳
  232. public static String timeMillisStr() {
  233. SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
  234. String format = df.format(new Date());
  235. long timeMillis = System.currentTimeMillis();
  236. return format + "_" + timeMillis + "_";
  237. }
  238. //返回年月日时分秒
  239. public static String dateStr() {
  240. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
  241. String format = df.format(new Date());
  242. return format + "_";
  243. }
  244. /**
  245. * 删除指定文件夹下所有文件
  246. * @param path 文件夹完整绝对路径
  247. * @return
  248. */
  249. public static boolean delAllFile(String path) {
  250. boolean flag = false;
  251. File file = new File(path);
  252. if (!file.exists()) {
  253. return flag;
  254. }
  255. if (!file.isDirectory()) {
  256. return flag;
  257. }
  258. String[] tempList = file.list();
  259. File temp = null;
  260. for (int i = 0; i < tempList.length; i++) {
  261. if (path.endsWith(File.separator)) {
  262. temp = new File(path + tempList[i]);
  263. } else {
  264. temp = new File(path + File.separator + tempList[i]);
  265. }
  266. if (temp.isFile()) {
  267. temp.delete();
  268. }
  269. if (temp.isDirectory()) {
  270. delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
  271. delFolder(path + "/" + tempList[i]);//再删除空文件夹
  272. // delAllFile(path + tempList[i]);//先删除文件夹里面的文件
  273. // delFolder(path + tempList[i]);//再删除空文件夹
  274. flag = true;
  275. }
  276. }
  277. return flag;
  278. }
  279. /**
  280. * 根据路径删除指定的目录,无论存在与否
  281. *
  282. * @param sPath 要删除的目录path
  283. * @return 删除成功返回 true,否则返回 false。
  284. */
  285. public static boolean deleteFolder(String sPath) {
  286. boolean flag = false;
  287. File file = new File(sPath);
  288. // 判断目录或文件是否存在
  289. if (!file.exists()) { // 不存在返回 false
  290. return flag;
  291. } else {
  292. // 判断是否为文件
  293. if (file.isFile()) { // 为文件时调用删除文件方法
  294. return deleteFile(sPath);
  295. } else { // 为目录时调用删除目录方法
  296. return deleteDirectory(sPath);
  297. }
  298. }
  299. }
  300. /**
  301. * 删除目录以及目录下的文件
  302. *
  303. * @param sPath 被删除目录的路径
  304. * @return 目录删除成功返回true,否则返回false
  305. */
  306. public static boolean deleteDirectory(String sPath) {
  307. //如果sPath不以文件分隔符结尾,自动添加文件分隔符
  308. if (!sPath.endsWith(File.separator)) {
  309. sPath = sPath + File.separator;
  310. }
  311. File dirFile = new File(sPath);
  312. //如果dir对应的文件不存在,或者不是一个目录,则退出
  313. if (!dirFile.exists() || !dirFile.isDirectory()) {
  314. return false;
  315. }
  316. boolean flag = true;
  317. //删除文件夹下的所有文件(包括子目录)
  318. File[] files = dirFile.listFiles();
  319. for (int i = 0; i < files.length; i++) {
  320. //删除子文件
  321. if (files[i].isFile()) {
  322. flag = deleteFile(files[i].getAbsolutePath());
  323. if (!flag) {
  324. break;
  325. }
  326. } //删除子目录
  327. else {
  328. flag = deleteDirectory(files[i].getAbsolutePath());
  329. if (!flag) {
  330. break;
  331. }
  332. }
  333. }
  334. if (!flag) {
  335. return false;
  336. }
  337. //删除当前目录
  338. if (dirFile.delete()) {
  339. return true;
  340. } else {
  341. return false;
  342. }
  343. }
  344. /**
  345. * 删除文件夹或删除文件
  346. * @param folderPath 文件夹完整绝对路径
  347. */
  348. public static void delFolder(String folderPath) {
  349. try {
  350. // File file = new File(folderPath);
  351. // if (file.exists()){
  352. //删除完里面所有内容
  353. delAllFile(folderPath);
  354. String filePath = folderPath;
  355. filePath = filePath.toString();
  356. File myFilePath = new File(filePath);
  357. //删除空文件夹
  358. myFilePath.delete();
  359. // }
  360. } catch (Exception e) {
  361. e.printStackTrace();
  362. }
  363. }
  364. /**
  365. * zip解压
  366. * @param zipFileName zip源文件
  367. * @param destDirPath 解压后的目标文件夹
  368. * @throws RuntimeException 解压失败会抛出运行时异常
  369. */
  370. public static boolean unzip(String zipFileName, String destDirPath) throws RuntimeException {
  371. File srcFile = new File(zipFileName);
  372. long start = System.currentTimeMillis();
  373. // 判断源文件是否存在
  374. if (!srcFile.exists()) {
  375. throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
  376. }
  377. // 开始解压
  378. ZipFile zipFile = null;
  379. try {
  380. zipFile = new ZipFile(srcFile, Charset.forName("gbk"));
  381. Enumeration<?> entries = zipFile.entries();
  382. while (entries.hasMoreElements()) {
  383. ZipEntry entry = (ZipEntry) entries.nextElement();
  384. // log.info("解压: " + entry.getName());
  385. // 如果是文件夹,就创建个文件夹
  386. if (entry.isDirectory()) {
  387. String dirPath = destDirPath + "/" + entry.getName();
  388. File dir = new File(dirPath);
  389. dir.mkdirs();
  390. } else {
  391. // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
  392. File targetFile = new File(destDirPath + "/" + entry.getName());
  393. // 保证这个文件的父文件夹必须要存在
  394. if(!targetFile.getParentFile().exists()){
  395. targetFile.getParentFile().mkdirs();
  396. }
  397. targetFile.createNewFile();
  398. // 将压缩文件内容写入到这个文件中
  399. InputStream is = zipFile.getInputStream(entry);
  400. FileOutputStream fos = new FileOutputStream(targetFile);
  401. int len;
  402. byte[] buf = new byte[1024];
  403. while ((len = is.read(buf)) != -1) {
  404. fos.write(buf, 0, len);
  405. }
  406. // 关流顺序,先打开的后关闭
  407. fos.close();
  408. is.close();
  409. }
  410. }
  411. long end = System.currentTimeMillis();
  412. log.info("解压完成,耗时:" + (end - start) +" ms");
  413. } catch (Exception e) {
  414. throw new RuntimeException("unzip error from ZipUtils", e);
  415. } finally {
  416. if(zipFile != null){
  417. try {
  418. zipFile.close();
  419. } catch (IOException e) {
  420. e.printStackTrace();
  421. }
  422. }
  423. }
  424. return true;
  425. }
  426. /**
  427. * 读取json 文件, Linux版
  428. */
  429. public static String readJsonLinux(String path){
  430. String param = FileUtils.readFile(path);
  431. return param;
  432. }
  433. public static void main(String[] args) {
  434. // unzip("F:\\test\\a1_shp2.zip", "F:\\test\\");
  435. // 这个是可以的,没有目录结构
  436. // unzip("F:\\test\\cesium\\clip.zip", "F:\\test\\cesium\\");
  437. // 这个有目录的,会失败
  438. // File file = new File("F:\\test\\clip.zip");
  439. unzip("F:\\test\\clip.zip", "F:\\test\\");
  440. }
  441. }