FileUtil.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. /*
  2. * FileName:FileUtil.java
  3. * <p>
  4. * Copyright (c) 2017-2020, <a href="http://www.webcsn.com">hermit (794890569@qq.com)</a>.
  5. * <p>
  6. * Licensed under the GNU General Public License, Version 3 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. * <p>
  10. * http://www.gnu.org/licenses/gpl-3.0.html
  11. * <p>
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. */
  19. package cn.com.lzt.common.util;
  20. import cn.com.lzt.core.common.Identities;
  21. import org.apache.commons.io.FileUtils;
  22. import java.io.*;
  23. import java.math.BigDecimal;
  24. import java.net.URL;
  25. import java.nio.ByteBuffer;
  26. import java.nio.channels.FileChannel;
  27. import java.util.ArrayList;
  28. import java.util.Collections;
  29. import java.util.List;
  30. import java.util.regex.Matcher;
  31. /**
  32. * 功能:文件操作工具类
  33. * @author
  34. *
  35. * mobile enterprise application platform
  36. * Version 0.1
  37. */
  38. public class FileUtil {
  39. /**
  40. * 获得去除扩展名的文件名
  41. * @param oldFilename
  42. * @return
  43. */
  44. public static String removeExtension(String oldFilename) {
  45. final File oldFile = new File(oldFilename);
  46. final int iExtPos = oldFile.getName().lastIndexOf('.');
  47. if (iExtPos != -1) {
  48. final String parentPath = oldFilename.substring(0,
  49. oldFilename.length() - oldFile.getName().length());
  50. return parentPath + oldFile.getName().substring(0, iExtPos);
  51. }
  52. return oldFilename;
  53. }
  54. /**
  55. * 返回文件名(比如abc.jpg)
  56. * @param path
  57. * @return
  58. */
  59. public static String getFileName(String path){
  60. if(ValidateUtil.isNull(path))return null;
  61. final int p = path.lastIndexOf(File.separatorChar);
  62. if (p != -1) {
  63. return path.substring(p + 1);
  64. } else {
  65. return "";
  66. }
  67. }
  68. /**
  69. * 返回文件名
  70. * @param file 文件对象
  71. * @param prefixDir 取文件地址前缀
  72. * @return
  73. */
  74. public static String getFileName(File file,File prefixDir){
  75. if(file==null)return null;
  76. if(prefixDir==null){
  77. return file.getName();
  78. }else{
  79. return StringUtil.substring(file.getPath(), prefixDir.getPath().length()+1, 0xFFFF);
  80. }
  81. }
  82. /**
  83. * 返回文件所在目录
  84. * @param path
  85. * @return
  86. */
  87. public static String getFileDirectory(String path){
  88. if(ValidateUtil.isNull(path))return null;
  89. final int p = path.lastIndexOf(File.separatorChar);
  90. if (p != -1) {
  91. return path.substring(0, p);
  92. } else {
  93. return "";
  94. }
  95. }
  96. /**
  97. * 更改扩展名
  98. * @param oldFilename
  99. * @param newExtension
  100. * @return
  101. */
  102. public static String changeExtension(String oldFilename, String newExtension) {
  103. String result = removeExtension(oldFilename);
  104. if (newExtension.length() != 0) {
  105. result = StringUtil.concat(result,".",newExtension);
  106. }
  107. return result;
  108. }
  109. /**
  110. * 获得文件扩展名
  111. * @param file
  112. * @return
  113. */
  114. public static String getExtension(File file) {
  115. final int ipos = file.getName().lastIndexOf(".");
  116. if (ipos != -1) {
  117. return file.getName().substring(ipos + 1);
  118. } else {
  119. return StringUtil.EMPTY_STRING;
  120. }
  121. }
  122. /**
  123. * 获得文件的扩展名
  124. * @param fileName
  125. * @return
  126. */
  127. public static String getExtension(String fileName){
  128. if(ValidateUtil.isNull(fileName))return "";
  129. return fileName.substring(fileName.lastIndexOf(".")+1);
  130. }
  131. /**
  132. * 获得文件格式问yyyyMMddHHmmss的文件名
  133. *
  134. * @return String format as "yyyyMMddHHmmss"
  135. */
  136. public static String getTempFileName() {
  137. return Identities.uuid()+".tmp";
  138. }
  139. /**
  140. * 剪切文件
  141. * @param sourceFile
  142. * @param destFile
  143. */
  144. public static void cutFile(File sourceFile, File destFile){
  145. copyFile(sourceFile,destFile);
  146. sourceFile.delete();
  147. }
  148. /**
  149. * 复制文件
  150. * @param sourceFile
  151. * @param destFile
  152. * @throws IOException
  153. */
  154. public static void copyFile(File sourceFile, File destFile) {
  155. try {
  156. if (sourceFile.equals(destFile)) {
  157. return;
  158. }
  159. if (!destFile.getParentFile().exists() && !destFile.getParentFile().mkdirs()) {
  160. throw new IOException("Cannot create directory " + destFile.getParent());
  161. }
  162. final int BUFFER = 2048;
  163. try (BufferedInputStream source = new BufferedInputStream(new FileInputStream(sourceFile), BUFFER)) {
  164. try (BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(destFile), BUFFER)) {
  165. int count;
  166. byte data[] = new byte[BUFFER];
  167. while ((count = source.read(data, 0, BUFFER)) != -1) {
  168. dest.write(data, 0, count);
  169. }
  170. }
  171. }
  172. } catch (Exception e) {
  173. e.printStackTrace();
  174. }
  175. }
  176. /**
  177. * 删除子目录和子文件
  178. * @param directory
  179. * @return
  180. */
  181. public static boolean deleteChildren(File directory) {
  182. if(!directory.canRead())return false;
  183. File[] files = directory.listFiles();
  184. for (int i = 0; i < files.length; i++) {
  185. if (files[i].isDirectory()) {
  186. if (!deleteChildren(files[i]) || !files[i].delete()) {
  187. return false;
  188. }
  189. } else if (!files[i].delete()) {
  190. return false;
  191. }
  192. }
  193. return directory.delete();
  194. }
  195. /**
  196. * 复制文件夹包括里面的文件
  197. * @param fromDirectory
  198. * @param toDirectory
  199. * @throws FileNotFoundException
  200. * @throws IOException
  201. */
  202. public static void copyDirectory(File fromDirectory, File toDirectory) throws FileNotFoundException, IOException {
  203. if (!toDirectory.exists() && !toDirectory.mkdirs()) {
  204. throw new IllegalStateException("Cannot create directory " + toDirectory.getAbsolutePath());
  205. }
  206. File[] fromFiles = fromDirectory.listFiles();
  207. for (int i = 0; i < fromFiles.length; i++) {
  208. File toFile = new File(toDirectory, fromFiles[i].getName());
  209. if (fromFiles[i].isFile()) {
  210. copyFile(fromFiles[i], toFile);
  211. }else {
  212. copyDirectory(fromFiles[i], toFile);
  213. }
  214. }
  215. }
  216. /**
  217. * 删除文件
  218. * @param files
  219. * @return
  220. */
  221. public static boolean delete(String... files){
  222. List<File> list = new ArrayList<File>();
  223. for(String file : files)
  224. list.add(new File(file));
  225. return delete(list);
  226. }
  227. /**
  228. * 删除指定文件
  229. * @param file
  230. * @return
  231. */
  232. public static boolean delete(File file){
  233. return delete(DataUtil.getList(file));
  234. }
  235. /**
  236. * 删除文件数组
  237. * @param files
  238. * @return
  239. */
  240. public static boolean delete(List<File> files) {
  241. for (File file :files) {
  242. if(file.exists()){
  243. if(file.isFile()){
  244. file.delete();
  245. }else if(file.isDirectory()){
  246. File fs[] = file.listFiles();
  247. for(int i=0;i<fs.length;i++){
  248. delete(fs[i]);
  249. }
  250. }
  251. file.delete();
  252. }else{
  253. return false;
  254. }
  255. }
  256. return true;
  257. }
  258. /**
  259. * 获得文件夹中的文件列表
  260. * @param directory
  261. * @return
  262. */
  263. public static List<File> getFiles(File directory) {
  264. return getFiles(directory,null);
  265. }
  266. /**
  267. * 获得文件夹中的指定规则的文件列表
  268. * @param directory
  269. * @param regex
  270. * @return
  271. */
  272. public static List<File> getFiles(File directory,String regex){
  273. if(!directory.isDirectory())return Collections.emptyList();
  274. List<File> result = new ArrayList<File>();
  275. File[] files = directory.listFiles();
  276. for (int i = 0; i < files.length; i++) {
  277. if (files[i].isFile() && (ValidateUtil.isNull(regex) || ValidateUtil.isRegex(files[i].getName(), regex))) {
  278. result.add(files[i]);
  279. } else if(files[i].isDirectory()){
  280. result.addAll(getFiles(files[i],regex));
  281. }
  282. }
  283. return result;
  284. }
  285. /**
  286. * 读取文件到stream
  287. * @param file
  288. * @return
  289. */
  290. public static byte[] readFileStream(File file)throws Exception{
  291. return readFileStream(file.getAbsolutePath());
  292. }
  293. /**
  294. * 读取文件到stream
  295. * @param path
  296. * @return
  297. */
  298. public static byte[] readFileStream(String path)
  299. throws Exception {
  300. byte[] bytes = null;
  301. try (FileInputStream fis = new FileInputStream(path)) {
  302. bytes = new byte[fis.available()];
  303. fis.read(bytes);
  304. }
  305. return bytes;
  306. }
  307. /**
  308. * 字节数组转换成输入流
  309. * @param buf
  310. * @return
  311. */
  312. public static InputStream byteArray2InputStream(byte[] buf) {
  313. return new ByteArrayInputStream(buf);
  314. }
  315. /**
  316. * 输入流转byte数组
  317. * @param inputStream
  318. * @return
  319. * @throws IOException
  320. */
  321. public static byte[] inputStream2ByteArray(InputStream inputStream)
  322. throws IOException {
  323. ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
  324. byte[] buff = new byte[100];
  325. int rc = 0;
  326. while ((rc = inputStream.read(buff, 0, 100)) > 0) {
  327. swapStream.write(buff, 0, rc);
  328. }
  329. byte[] in2b = swapStream.toByteArray();
  330. return in2b;
  331. }
  332. /**
  333. * 读取文件
  334. * @param filename
  335. * @return
  336. * @throws IOException
  337. */
  338. public static String readFile(String filename) {
  339. return readFile(new File(filename));
  340. }
  341. /**
  342. * 读取文件内容
  343. * @param file
  344. * @return
  345. */
  346. public static String readFile(File file){
  347. String text = null;
  348. try {
  349. text = FileUtils.readFileToString(file);
  350. } catch (IOException e) {
  351. e.printStackTrace();
  352. }
  353. return text;
  354. }
  355. /**
  356. * 读出文件到output
  357. * @param file
  358. * @param output
  359. * @throws IOException
  360. */
  361. public static void readFile(File file, OutputStream output)
  362. throws IOException {
  363. FileChannel fc = null;
  364. try (FileInputStream input = new FileInputStream(file)) {
  365. fc = input.getChannel();
  366. ByteBuffer buffer = ByteBuffer.allocate(4096);
  367. for (;;) {
  368. buffer.clear();
  369. int n = fc.read(buffer);
  370. if (n == (-1))
  371. break;
  372. output.write(buffer.array(), 0, buffer.position());
  373. }
  374. }
  375. }
  376. /**
  377. * 读取文件
  378. * @param file
  379. * @param encoding
  380. * @return
  381. */
  382. public static String readFile(File file,String encoding){
  383. String text = null;
  384. try {
  385. text = FileUtils.readFileToString(file, encoding);
  386. } catch (IOException e) {
  387. e.printStackTrace();
  388. }
  389. return text;
  390. }
  391. /**
  392. * 读取文件到数组每行一个数组中的字符串
  393. * Read file to array of String.
  394. * @param file
  395. * @return
  396. * @throws IOException
  397. */
  398. public static String[] readFileToArray(File file) throws IOException {
  399. List<String> lines = FileUtils.readLines(file);
  400. return lines.toArray(new String[lines.size()]);
  401. }
  402. /**
  403. * 写出文件
  404. * @param file
  405. * @param text
  406. * @param encoding
  407. * @throws IOException
  408. */
  409. public static void writeFile(String filePath,String text,String encoding)throws IOException{
  410. File file = new File(filePath);
  411. FileUtil.writeFile(file, text, encoding);
  412. }
  413. /**
  414. * 写出文件
  415. * @param file
  416. * @param text
  417. * @param encoding
  418. * @throws IOException
  419. */
  420. public static void writeFile(File file,String text,String encoding)throws IOException{
  421. FileUtils.writeStringToFile(file, text, encoding);
  422. }
  423. /**
  424. * 验证文件是否存在
  425. * @param strings 文件地址组合 strings[0] + strings[1] +strings[2]
  426. */
  427. public static boolean exists(Object...objs) {
  428. try{
  429. return new File(StringUtil.concat(objs)).exists();
  430. }catch(Exception e){
  431. return false;
  432. }
  433. }
  434. /**
  435. * 查看文件件是否存在不存就创建
  436. * @param thisImageDir
  437. */
  438. public static void mkdirs(String dir) {
  439. if(!(new File(dir).isDirectory())){
  440. try{
  441. new File(dir).mkdirs();
  442. }catch(SecurityException e){
  443. e.printStackTrace();
  444. }
  445. }
  446. }
  447. /**
  448. * 写出文件
  449. * @param filePath
  450. * @param _byte
  451. */
  452. public static void writeFile(String filePath,byte[] _byte){
  453. ByteArrayInputStream bais = new ByteArrayInputStream(_byte);
  454. try{
  455. writeFile(new File(filePath),bais);
  456. }catch(Exception e){
  457. e.printStackTrace();
  458. }finally{
  459. FileUtil.close(bais);
  460. }
  461. }
  462. /**
  463. * 写出文件
  464. * @param file
  465. * @param is
  466. * @param encoding
  467. */
  468. public static void writeFile(File file, InputStream is) {
  469. OutputStream os = null;
  470. try {
  471. os = new FileOutputStream(file);
  472. int size = is.available();
  473. for (int j = 0; j < size; j++) {
  474. os.write(is.read());
  475. }
  476. } catch (FileNotFoundException e) {
  477. e.printStackTrace();
  478. } catch (IOException e) {
  479. e.printStackTrace();
  480. }finally{
  481. FileUtil.close(os);
  482. FileUtil.close(is);
  483. }
  484. }
  485. /**
  486. * 获得文件大小
  487. * @param f
  488. * @return
  489. */
  490. public static long getFileSize(File f) {
  491. if(f==null || !f.exists())return 0;
  492. long s=0;
  493. FileInputStream fis = null;
  494. try{
  495. fis = new FileInputStream(f);
  496. s = fis.available();
  497. }catch(IOException e){
  498. e.printStackTrace();
  499. }finally{
  500. FileUtil.close(fis);
  501. }
  502. return s;
  503. }
  504. /**
  505. * 获得文件的KB大小
  506. * @param f
  507. * @return
  508. */
  509. public static BigDecimal getKBFileSize(File f){
  510. return BigDecimal.valueOf(getFileSize(f)).divide(BigDecimal.valueOf(1024)).setScale(2, BigDecimal.ROUND_HALF_UP);
  511. }
  512. /**
  513. * 获得文件的MB大小
  514. * @param f
  515. * @return
  516. */
  517. public static BigDecimal getMBFileSize(File f){
  518. return getKBFileSize(f).divide(BigDecimal.valueOf(1024)).setScale(2, BigDecimal.ROUND_HALF_UP);
  519. }
  520. /**
  521. * 获得友好的文件大小
  522. * @param file
  523. * @return
  524. */
  525. public static String getFriendlyFileSize(File file){
  526. long size = getFileSize(file);
  527. if(size < 1024){
  528. return StringUtil.concat(BigDecimal.valueOf(size).setScale(2, BigDecimal.ROUND_HALF_UP),"B");
  529. }else if(size < 1024*1024){
  530. return StringUtil.concat(BigDecimal.valueOf(size).divide(BigDecimal.valueOf(1024)).setScale(2, BigDecimal.ROUND_HALF_UP),"KB");
  531. }else if(size < 1024*1024*1024){
  532. return StringUtil.concat(BigDecimal.valueOf(size).divide(BigDecimal.valueOf(1024)).divide(BigDecimal.valueOf(1024)).setScale(2, BigDecimal.ROUND_HALF_UP),"MB");
  533. }else{
  534. return StringUtil.concat(BigDecimal.valueOf(size).divide(BigDecimal.valueOf(1024)).divide(BigDecimal.valueOf(1024)).divide(BigDecimal.valueOf(1024)).setScale(2, BigDecimal.ROUND_HALF_UP),"GB");
  535. }
  536. }
  537. /**
  538. * 替换文件的分隔符
  539. * @param removeExtension
  540. * @return
  541. */
  542. public static String replaceSeparator(String src,String to) {
  543. return StringUtil.getNonNull(src).replaceAll( Matcher.quoteReplacement(File.separator), to);
  544. }
  545. /**
  546. * 获得文本的行数
  547. * @param file
  548. * @return
  549. */
  550. public static int getFileLines(File file){
  551. int lines = 0;
  552. if(file.canRead()){
  553. BufferedReader br = null;
  554. try {
  555. br = new BufferedReader(new FileReader(file));
  556. while (br.readLine() != null) {
  557. lines ++ ;
  558. }
  559. br.close();
  560. } catch (FileNotFoundException e) {
  561. e.printStackTrace();
  562. } catch (IOException e) {
  563. e.printStackTrace();
  564. } finally{
  565. FileUtil.close(br);
  566. }
  567. }
  568. return lines;
  569. }
  570. /**
  571. * 读取远程文件到本地
  572. * @param fileUrl 远程文件url 如:http://www.baidu.com/1.jpg
  573. * @param localFilePath 本地硬盘绝对路径 c:/1.jpg
  574. * @return
  575. */
  576. public static boolean readDistanceFile(String fileUrl, String localFilePath) {
  577. BufferedInputStream bis = null;
  578. OutputStream bos = null;
  579. URL url = null;
  580. try {
  581. // 实例化url
  582. url = new URL(fileUrl);
  583. // 载入图片到输入流
  584. bis = new BufferedInputStream(url.openStream());
  585. // 实例化存储字节数组
  586. byte[] bytes = new byte[100];
  587. // 设置写入路径以及图片名称
  588. bos = new FileOutputStream(new File(localFilePath));
  589. int len;
  590. while ((len = bis.read(bytes)) > 0) {
  591. bos.write(bytes, 0, len);
  592. }
  593. return true;
  594. } catch (Exception e) {
  595. // 如果图片未找到
  596. return false;
  597. } finally {
  598. // 关闭输出流
  599. FileUtil.close(bis);
  600. FileUtil.close(bos);
  601. }
  602. }
  603. /**
  604. * 获得文件编码
  605. * @param file
  606. * @return
  607. */
  608. public static String getFileCharacterEncoding(File file){
  609. return CharsetUtil.getLocalteFileEncode(file);
  610. }
  611. /**
  612. * 关闭流
  613. * @param os
  614. */
  615. public static void close(Closeable os){
  616. if(os!=null){
  617. try {
  618. os.close();
  619. } catch (IOException e) {
  620. e.printStackTrace();
  621. }
  622. }
  623. }
  624. /**
  625. * 输入流进行MD5散列
  626. * @param input
  627. * @return
  628. * @throws IOException
  629. */
  630. public static byte[] md5(InputStream input) throws IOException {
  631. return HashUtil.digest(input, HashUtil.MD5);
  632. }
  633. /**
  634. * 输入流进行SHA散列
  635. * @param input
  636. * @return
  637. * @throws IOException
  638. */
  639. public static byte[] sha1(InputStream input) throws IOException {
  640. return HashUtil.digest(input, HashUtil.SHA1);
  641. }
  642. }