FileUtils.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. *
  80. * 1.先将文件中的内容读入到缓冲输入流中
  81. * 2.将输入流中的数据通过缓冲输出流写入到目标文件中
  82. * 3.关闭输入流和输出流
  83. *
  84. * in: 输入流
  85. * path: 保持位置
  86. */
  87. public static int downloanAndGetResolutionRate(InputStream in, String fileFullPath, boolean needCheckResolutin) throws IOException {
  88. // 输入缓冲流
  89. File file = new File(fileFullPath);
  90. if(file.exists()){
  91. deleteFile(fileFullPath);
  92. file = new File(fileFullPath);
  93. }
  94. BufferedInputStream inputBuff = new BufferedInputStream(in);
  95. // 输出缓冲流
  96. BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
  97. int len = 0;
  98. byte[] buffer = new byte[1024];
  99. while ((len = inputBuff.read(buffer)) != -1) {
  100. stream.write(buffer, 0, len);
  101. }
  102. stream.flush();
  103. stream.close();
  104. inputBuff.close();
  105. int totalResolutinRate = -1;
  106. if(needCheckResolutin){
  107. SimpleImageInfo simpleImageInfo = new SimpleImageInfo(file);
  108. if(null != simpleImageInfo){
  109. totalResolutinRate = simpleImageInfo.getWidth()*simpleImageInfo.getHeight();
  110. }
  111. }
  112. return totalResolutinRate;
  113. }
  114. /**
  115. * 删除单个文件
  116. *
  117. * @param fileName 要删除的文件的文件名
  118. * @return 单个文件删除成功返回true,否则返回false
  119. */
  120. public static boolean deleteFile(String fileName) {
  121. File file = new File(fileName);
  122. if (file.exists() && file.isFile()) {
  123. if (file.delete()) {
  124. return true;
  125. } else {
  126. return false;
  127. }
  128. } else {
  129. return false;
  130. }
  131. }
  132. /**
  133. *
  134. * @param content base64内容
  135. * @param path 输出文件路径,需要后缀名
  136. * @return
  137. */
  138. public static boolean base64ToFileWriter(String content, String path) {
  139. if (content == null) {
  140. return false;
  141. }
  142. try {
  143. byte[] b = Base64.getDecoder().decode(content);
  144. // processing data
  145. for (int i = 0; i < b.length; ++i) {
  146. if (b[i] < 0) {
  147. b[i] += 256;
  148. }
  149. }
  150. OutputStream out = new FileOutputStream(path);
  151. out.write(b);
  152. out.flush();
  153. out.close();
  154. return true;
  155. } catch (Exception e) {
  156. return false;
  157. }
  158. }
  159. /**
  160. * 读取文件方法
  161. * @param Path 文件路径
  162. * @return 返回内容
  163. */
  164. public static String readFile(String Path){
  165. BufferedReader reader = null;
  166. String laststr = "";
  167. try{
  168. FileInputStream fileInputStream = new FileInputStream(Path);
  169. InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
  170. reader = new BufferedReader(inputStreamReader);
  171. String tempString = null;
  172. while((tempString = reader.readLine()) != null){
  173. laststr += tempString;
  174. }
  175. reader.close();
  176. }catch(IOException e){
  177. e.printStackTrace();
  178. }finally{
  179. if(reader != null){
  180. try {
  181. reader.close();
  182. } catch (IOException e) {
  183. e.printStackTrace();
  184. }
  185. }
  186. }
  187. return laststr;
  188. }
  189. /**
  190. * 生成文件
  191. * @param content 内容
  192. * @param path 生成路径
  193. * @throws IOException
  194. */
  195. public static void fileWriter(String content, String path) throws IOException {
  196. FileWriter writer = new FileWriter(path);
  197. writer.write(content);
  198. writer.flush();
  199. writer.close();
  200. }
  201. public static void writeFile(String filePath,String str) throws IOException {
  202. File fout = new File(filePath);
  203. if(!fout.getParentFile().exists()){
  204. fout.getParentFile().mkdirs();
  205. }
  206. if(!fout.exists()){
  207. fout.createNewFile();
  208. }
  209. FileOutputStream fos = new FileOutputStream(fout);
  210. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
  211. bw.write(str);
  212. bw.close();
  213. }
  214. // 获取时间戳
  215. public static String timeMillisStr() {
  216. SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
  217. String format = df.format(new Date());
  218. long timeMillis = System.currentTimeMillis();
  219. return format + "_" + timeMillis + "_";
  220. }
  221. //返回年月日时分秒
  222. public static String dateStr() {
  223. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
  224. String format = df.format(new Date());
  225. return format + "_";
  226. }
  227. /**
  228. * 删除指定文件夹下所有文件
  229. * @param path 文件夹完整绝对路径
  230. * @return
  231. */
  232. public static boolean delAllFile(String path) {
  233. boolean flag = false;
  234. File file = new File(path);
  235. if (!file.exists()) {
  236. return flag;
  237. }
  238. if (!file.isDirectory()) {
  239. return flag;
  240. }
  241. String[] tempList = file.list();
  242. File temp = null;
  243. for (int i = 0; i < tempList.length; i++) {
  244. if (path.endsWith(File.separator)) {
  245. temp = new File(path + tempList[i]);
  246. } else {
  247. temp = new File(path + File.separator + tempList[i]);
  248. }
  249. if (temp.isFile()) {
  250. temp.delete();
  251. }
  252. if (temp.isDirectory()) {
  253. delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
  254. delFolder(path + "/" + tempList[i]);//再删除空文件夹
  255. // delAllFile(path + tempList[i]);//先删除文件夹里面的文件
  256. // delFolder(path + tempList[i]);//再删除空文件夹
  257. flag = true;
  258. }
  259. }
  260. return flag;
  261. }
  262. /**
  263. * 删除文件夹或删除文件
  264. * @param folderPath 文件夹完整绝对路径
  265. */
  266. public static void delFolder(String folderPath) {
  267. try {
  268. // File file = new File(folderPath);
  269. // if (file.exists()){
  270. //删除完里面所有内容
  271. delAllFile(folderPath);
  272. String filePath = folderPath;
  273. filePath = filePath.toString();
  274. File myFilePath = new File(filePath);
  275. //删除空文件夹
  276. myFilePath.delete();
  277. // }
  278. } catch (Exception e) {
  279. e.printStackTrace();
  280. }
  281. }
  282. /**
  283. * zip解压
  284. * @param zipFileName zip源文件
  285. * @param destDirPath 解压后的目标文件夹
  286. * @throws RuntimeException 解压失败会抛出运行时异常
  287. */
  288. public static boolean unzip(String zipFileName, String destDirPath) throws RuntimeException {
  289. File srcFile = new File(zipFileName);
  290. long start = System.currentTimeMillis();
  291. // 判断源文件是否存在
  292. if (!srcFile.exists()) {
  293. throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
  294. }
  295. // 开始解压
  296. ZipFile zipFile = null;
  297. try {
  298. zipFile = new ZipFile(srcFile, Charset.forName("gbk"));
  299. Enumeration<?> entries = zipFile.entries();
  300. while (entries.hasMoreElements()) {
  301. ZipEntry entry = (ZipEntry) entries.nextElement();
  302. // log.info("解压: " + entry.getName());
  303. // 如果是文件夹,就创建个文件夹
  304. if (entry.isDirectory()) {
  305. String dirPath = destDirPath + "/" + entry.getName();
  306. File dir = new File(dirPath);
  307. dir.mkdirs();
  308. } else {
  309. // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
  310. File targetFile = new File(destDirPath + "/" + entry.getName());
  311. // 保证这个文件的父文件夹必须要存在
  312. if(!targetFile.getParentFile().exists()){
  313. targetFile.getParentFile().mkdirs();
  314. }
  315. targetFile.createNewFile();
  316. // 将压缩文件内容写入到这个文件中
  317. InputStream is = zipFile.getInputStream(entry);
  318. FileOutputStream fos = new FileOutputStream(targetFile);
  319. int len;
  320. byte[] buf = new byte[1024];
  321. while ((len = is.read(buf)) != -1) {
  322. fos.write(buf, 0, len);
  323. }
  324. // 关流顺序,先打开的后关闭
  325. fos.close();
  326. is.close();
  327. }
  328. }
  329. long end = System.currentTimeMillis();
  330. log.info("解压完成,耗时:" + (end - start) +" ms");
  331. } catch (Exception e) {
  332. throw new RuntimeException("unzip error from ZipUtils", e);
  333. } finally {
  334. if(zipFile != null){
  335. try {
  336. zipFile.close();
  337. } catch (IOException e) {
  338. e.printStackTrace();
  339. }
  340. }
  341. }
  342. return true;
  343. }
  344. /**
  345. * 读取json 文件, Linux版
  346. */
  347. public static String readJsonLinux(String path){
  348. String param = FileUtils.readFile(path);
  349. return param;
  350. }
  351. public static void main(String[] args) {
  352. // unzip("F:\\test\\a1_shp2.zip", "F:\\test\\");
  353. // 这个是可以的,没有目录结构
  354. // unzip("F:\\test\\cesium\\clip.zip", "F:\\test\\cesium\\");
  355. // 这个有目录的,会失败
  356. // File file = new File("F:\\test\\clip.zip");
  357. unzip("F:\\test\\clip.zip", "F:\\test\\");
  358. }
  359. }