FileUtils.java 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  1. package com.cooleshow.base.utils;
  2. import android.app.Application;
  3. import android.content.ContentResolver;
  4. import android.content.ContentValues;
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.content.res.AssetFileDescriptor;
  8. import android.database.Cursor;
  9. import android.graphics.Bitmap;
  10. import android.graphics.BitmapFactory;
  11. import android.media.MediaScannerConnection;
  12. import android.net.Uri;
  13. import android.os.Build;
  14. import android.os.Environment;
  15. import android.os.StatFs;
  16. import android.provider.MediaStore;
  17. import android.provider.OpenableColumns;
  18. import android.text.TextUtils;
  19. import android.util.Base64;
  20. import android.util.Log;
  21. import java.io.BufferedInputStream;
  22. import java.io.BufferedOutputStream;
  23. import java.io.ByteArrayInputStream;
  24. import java.io.ByteArrayOutputStream;
  25. import java.io.File;
  26. import java.io.FileFilter;
  27. import java.io.FileInputStream;
  28. import java.io.FileNotFoundException;
  29. import java.io.FileOutputStream;
  30. import java.io.IOException;
  31. import java.io.InputStream;
  32. import java.io.OutputStream;
  33. import java.net.URL;
  34. import java.nio.file.Files;
  35. import java.security.DigestInputStream;
  36. import java.security.MessageDigest;
  37. import java.security.NoSuchAlgorithmException;
  38. import java.text.SimpleDateFormat;
  39. import java.util.ArrayList;
  40. import java.util.Collections;
  41. import java.util.Comparator;
  42. import java.util.Date;
  43. import java.util.List;
  44. import java.util.Locale;
  45. import javax.net.ssl.HttpsURLConnection;
  46. import okhttp3.ResponseBody;
  47. /**
  48. * <pre>
  49. * author: Blankj
  50. * blog : http://blankj.com
  51. * time : 2016/05/03
  52. * desc : utils about file
  53. * </pre>
  54. */
  55. public final class FileUtils {
  56. public static final String filesDirectory = "coolexiu";
  57. public static final String examDownloadDirectory = "examDownload";
  58. private static final String LINE_SEP = System.getProperty("line.separator");
  59. public static String getCacheDir(Context context) {
  60. String cacheDir = context.getExternalCacheDir().getAbsolutePath();
  61. return cacheDir;
  62. }
  63. private FileUtils() {
  64. throw new UnsupportedOperationException("u can't instantiate me...");
  65. }
  66. /**
  67. * Return the file by path.
  68. *
  69. * @param filePath The path of file.
  70. * @return the file
  71. */
  72. public static File getFileByPath(final String filePath) {
  73. return UtilsBridge.isSpace(filePath) ? null : new File(filePath);
  74. }
  75. /**
  76. * Return whether the file exists.
  77. *
  78. * @param file The file.
  79. * @return {@code true}: yes<br>{@code false}: no
  80. */
  81. public static boolean isFileExists(final File file) {
  82. if (file == null) return false;
  83. if (file.exists()) {
  84. return true;
  85. }
  86. return isFileExists(file.getAbsolutePath());
  87. }
  88. /**
  89. * Return whether the file exists.
  90. *
  91. * @param filePath The path of file.
  92. * @return {@code true}: yes<br>{@code false}: no
  93. */
  94. public static boolean isFileExists(final String filePath) {
  95. File file = getFileByPath(filePath);
  96. if (file == null) return false;
  97. if (file.exists()) {
  98. return true;
  99. }
  100. return isFileExistsApi29(filePath);
  101. }
  102. private static boolean isFileExistsApi29(String filePath) {
  103. if (Build.VERSION.SDK_INT >= 29) {
  104. try {
  105. Uri uri = Uri.parse(filePath);
  106. ContentResolver cr = Utils.getApp().getContentResolver();
  107. AssetFileDescriptor afd = cr.openAssetFileDescriptor(uri, "r");
  108. if (afd == null) return false;
  109. try {
  110. afd.close();
  111. } catch (IOException ignore) {
  112. }
  113. } catch (FileNotFoundException e) {
  114. return false;
  115. }
  116. return true;
  117. }
  118. return false;
  119. }
  120. /**
  121. * Rename the file.
  122. *
  123. * @param filePath The path of file.
  124. * @param newName The new name of file.
  125. * @return {@code true}: success<br>{@code false}: fail
  126. */
  127. public static boolean rename(final String filePath, final String newName) {
  128. return rename(getFileByPath(filePath), newName);
  129. }
  130. /**
  131. * Rename the file.
  132. *
  133. * @param file The file.
  134. * @param newName The new name of file.
  135. * @return {@code true}: success<br>{@code false}: fail
  136. */
  137. public static boolean rename(final File file, final String newName) {
  138. // file is null then return false
  139. if (file == null) return false;
  140. // file doesn't exist then return false
  141. if (!file.exists()) return false;
  142. // the new name is space then return false
  143. if (UtilsBridge.isSpace(newName)) return false;
  144. // the new name equals old name then return true
  145. if (newName.equals(file.getName())) return true;
  146. File newFile = new File(file.getParent() + File.separator + newName);
  147. // the new name of file exists then return false
  148. return !newFile.exists()
  149. && file.renameTo(newFile);
  150. }
  151. /**
  152. * Return whether it is a directory.
  153. *
  154. * @param dirPath The path of directory.
  155. * @return {@code true}: yes<br>{@code false}: no
  156. */
  157. public static boolean isDir(final String dirPath) {
  158. return isDir(getFileByPath(dirPath));
  159. }
  160. /**
  161. * Return whether it is a directory.
  162. *
  163. * @param file The file.
  164. * @return {@code true}: yes<br>{@code false}: no
  165. */
  166. public static boolean isDir(final File file) {
  167. return file != null && file.exists() && file.isDirectory();
  168. }
  169. /**
  170. * Return whether it is a file.
  171. *
  172. * @param filePath The path of file.
  173. * @return {@code true}: yes<br>{@code false}: no
  174. */
  175. public static boolean isFile(final String filePath) {
  176. return isFile(getFileByPath(filePath));
  177. }
  178. /**
  179. * Return whether it is a file.
  180. *
  181. * @param file The file.
  182. * @return {@code true}: yes<br>{@code false}: no
  183. */
  184. public static boolean isFile(final File file) {
  185. return file != null && file.exists() && file.isFile();
  186. }
  187. /**
  188. * Create a directory if it doesn't exist, otherwise do nothing.
  189. *
  190. * @param dirPath The path of directory.
  191. * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise
  192. */
  193. public static boolean createOrExistsDir(final String dirPath) {
  194. return createOrExistsDir(getFileByPath(dirPath));
  195. }
  196. /**
  197. * Create a directory if it doesn't exist, otherwise do nothing.
  198. *
  199. * @param file The file.
  200. * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise
  201. */
  202. public static boolean createOrExistsDir(final File file) {
  203. return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
  204. }
  205. /**
  206. * Create a file if it doesn't exist, otherwise do nothing.
  207. *
  208. * @param filePath The path of file.
  209. * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise
  210. */
  211. public static boolean createOrExistsFile(final String filePath) {
  212. return createOrExistsFile(getFileByPath(filePath));
  213. }
  214. /**
  215. * Create a file if it doesn't exist, otherwise do nothing.
  216. *
  217. * @param file The file.
  218. * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise
  219. */
  220. public static boolean createOrExistsFile(final File file) {
  221. if (file == null) return false;
  222. if (file.exists()) return file.isFile();
  223. if (!createOrExistsDir(file.getParentFile())) return false;
  224. try {
  225. return file.createNewFile();
  226. } catch (IOException e) {
  227. e.printStackTrace();
  228. return false;
  229. }
  230. }
  231. /**
  232. * Create a file if it doesn't exist, otherwise delete old file before creating.
  233. *
  234. * @param filePath The path of file.
  235. * @return {@code true}: success<br>{@code false}: fail
  236. */
  237. public static boolean createFileByDeleteOldFile(final String filePath) {
  238. return createFileByDeleteOldFile(getFileByPath(filePath));
  239. }
  240. /**
  241. * Create a file if it doesn't exist, otherwise delete old file before creating.
  242. *
  243. * @param file The file.
  244. * @return {@code true}: success<br>{@code false}: fail
  245. */
  246. public static boolean createFileByDeleteOldFile(final File file) {
  247. if (file == null) return false;
  248. // file exists and unsuccessfully delete then return false
  249. if (file.exists() && !file.delete()) return false;
  250. if (!createOrExistsDir(file.getParentFile())) return false;
  251. try {
  252. return file.createNewFile();
  253. } catch (IOException e) {
  254. e.printStackTrace();
  255. return false;
  256. }
  257. }
  258. /**
  259. * Copy the directory or file.
  260. *
  261. * @param srcPath The path of source.
  262. * @param destPath The path of destination.
  263. * @return {@code true}: success<br>{@code false}: fail
  264. */
  265. public static boolean copy(final String srcPath,
  266. final String destPath) {
  267. return copy(getFileByPath(srcPath), getFileByPath(destPath), null);
  268. }
  269. /**
  270. * Copy the directory or file.
  271. *
  272. * @param srcPath The path of source.
  273. * @param destPath The path of destination.
  274. * @param listener The replace listener.
  275. * @return {@code true}: success<br>{@code false}: fail
  276. */
  277. public static boolean copy(final String srcPath,
  278. final String destPath,
  279. final OnReplaceListener listener) {
  280. return copy(getFileByPath(srcPath), getFileByPath(destPath), listener);
  281. }
  282. /**
  283. * Copy the directory or file.
  284. *
  285. * @param src The source.
  286. * @param dest The destination.
  287. * @return {@code true}: success<br>{@code false}: fail
  288. */
  289. public static boolean copy(final File src,
  290. final File dest) {
  291. return copy(src, dest, null);
  292. }
  293. /**
  294. * Copy the directory or file.
  295. *
  296. * @param src The source.
  297. * @param dest The destination.
  298. * @param listener The replace listener.
  299. * @return {@code true}: success<br>{@code false}: fail
  300. */
  301. public static boolean copy(final File src,
  302. final File dest,
  303. final OnReplaceListener listener) {
  304. if (src == null) return false;
  305. if (src.isDirectory()) {
  306. return copyDir(src, dest, listener);
  307. }
  308. return copyFile(src, dest, listener);
  309. }
  310. /**
  311. * Copy the directory.
  312. *
  313. * @param srcDir The source directory.
  314. * @param destDir The destination directory.
  315. * @param listener The replace listener.
  316. * @return {@code true}: success<br>{@code false}: fail
  317. */
  318. private static boolean copyDir(final File srcDir,
  319. final File destDir,
  320. final OnReplaceListener listener) {
  321. return copyOrMoveDir(srcDir, destDir, listener, false);
  322. }
  323. /**
  324. * Copy the file.
  325. *
  326. * @param srcFile The source file.
  327. * @param destFile The destination file.
  328. * @param listener The replace listener.
  329. * @return {@code true}: success<br>{@code false}: fail
  330. */
  331. private static boolean copyFile(final File srcFile,
  332. final File destFile,
  333. final OnReplaceListener listener) {
  334. return copyOrMoveFile(srcFile, destFile, listener, false);
  335. }
  336. /**
  337. * Move the directory or file.
  338. *
  339. * @param srcPath The path of source.
  340. * @param destPath The path of destination.
  341. * @return {@code true}: success<br>{@code false}: fail
  342. */
  343. public static boolean move(final String srcPath,
  344. final String destPath) {
  345. return move(getFileByPath(srcPath), getFileByPath(destPath), null);
  346. }
  347. /**
  348. * Move the directory or file.
  349. *
  350. * @param srcPath The path of source.
  351. * @param destPath The path of destination.
  352. * @param listener The replace listener.
  353. * @return {@code true}: success<br>{@code false}: fail
  354. */
  355. public static boolean move(final String srcPath,
  356. final String destPath,
  357. final OnReplaceListener listener) {
  358. return move(getFileByPath(srcPath), getFileByPath(destPath), listener);
  359. }
  360. /**
  361. * Move the directory or file.
  362. *
  363. * @param src The source.
  364. * @param dest The destination.
  365. * @return {@code true}: success<br>{@code false}: fail
  366. */
  367. public static boolean move(final File src,
  368. final File dest) {
  369. return move(src, dest, null);
  370. }
  371. /**
  372. * Move the directory or file.
  373. *
  374. * @param src The source.
  375. * @param dest The destination.
  376. * @param listener The replace listener.
  377. * @return {@code true}: success<br>{@code false}: fail
  378. */
  379. public static boolean move(final File src,
  380. final File dest,
  381. final OnReplaceListener listener) {
  382. if (src == null) return false;
  383. if (src.isDirectory()) {
  384. return moveDir(src, dest, listener);
  385. }
  386. return moveFile(src, dest, listener);
  387. }
  388. /**
  389. * Move the directory.
  390. *
  391. * @param srcDir The source directory.
  392. * @param destDir The destination directory.
  393. * @param listener The replace listener.
  394. * @return {@code true}: success<br>{@code false}: fail
  395. */
  396. public static boolean moveDir(final File srcDir,
  397. final File destDir,
  398. final OnReplaceListener listener) {
  399. return copyOrMoveDir(srcDir, destDir, listener, true);
  400. }
  401. /**
  402. * Move the file.
  403. *
  404. * @param srcFile The source file.
  405. * @param destFile The destination file.
  406. * @param listener The replace listener.
  407. * @return {@code true}: success<br>{@code false}: fail
  408. */
  409. public static boolean moveFile(final File srcFile,
  410. final File destFile,
  411. final OnReplaceListener listener) {
  412. return copyOrMoveFile(srcFile, destFile, listener, true);
  413. }
  414. private static boolean copyOrMoveDir(final File srcDir,
  415. final File destDir,
  416. final OnReplaceListener listener,
  417. final boolean isMove) {
  418. if (srcDir == null || destDir == null) return false;
  419. // destDir's path locate in srcDir's path then return false
  420. String srcPath = srcDir.getPath() + File.separator;
  421. String destPath = destDir.getPath() + File.separator;
  422. if (destPath.contains(srcPath)) return false;
  423. if (!srcDir.exists() || !srcDir.isDirectory()) return false;
  424. if (!createOrExistsDir(destDir)) return false;
  425. File[] files = srcDir.listFiles();
  426. if (files != null && files.length > 0) {
  427. for (File file : files) {
  428. File oneDestFile = new File(destPath + file.getName());
  429. if (file.isFile()) {
  430. if (!copyOrMoveFile(file, oneDestFile, listener, isMove)) return false;
  431. } else if (file.isDirectory()) {
  432. if (!copyOrMoveDir(file, oneDestFile, listener, isMove)) return false;
  433. }
  434. }
  435. }
  436. return !isMove || deleteDir(srcDir);
  437. }
  438. private static boolean copyOrMoveFile(final File srcFile,
  439. final File destFile,
  440. final OnReplaceListener listener,
  441. final boolean isMove) {
  442. if (srcFile == null || destFile == null) return false;
  443. // srcFile equals destFile then return false
  444. if (srcFile.equals(destFile)) return false;
  445. // srcFile doesn't exist or isn't a file then return false
  446. if (!srcFile.exists() || !srcFile.isFile()) return false;
  447. if (destFile.exists()) {
  448. if (listener == null || listener.onReplace(srcFile, destFile)) {// require delete the old file
  449. if (!destFile.delete()) {// unsuccessfully delete then return false
  450. return false;
  451. }
  452. } else {
  453. return true;
  454. }
  455. }
  456. if (!createOrExistsDir(destFile.getParentFile())) return false;
  457. try {
  458. return UtilsBridge.writeFileFromIS(destFile.getAbsolutePath(), new FileInputStream(srcFile))
  459. && !(isMove && !deleteFile(srcFile));
  460. } catch (FileNotFoundException e) {
  461. e.printStackTrace();
  462. return false;
  463. }
  464. }
  465. /**
  466. * Delete the directory.
  467. *
  468. * @param filePath The path of file.
  469. * @return {@code true}: success<br>{@code false}: fail
  470. */
  471. public static boolean delete(final String filePath) {
  472. return delete(getFileByPath(filePath));
  473. }
  474. /**
  475. * Delete the directory.
  476. *
  477. * @param file The file.
  478. * @return {@code true}: success<br>{@code false}: fail
  479. */
  480. public static boolean delete(final File file) {
  481. if (file == null) return false;
  482. if (file.isDirectory()) {
  483. return deleteDir(file);
  484. }
  485. return deleteFile(file);
  486. }
  487. /**
  488. * Delete the directory.
  489. *
  490. * @param dir The directory.
  491. * @return {@code true}: success<br>{@code false}: fail
  492. */
  493. private static boolean deleteDir(final File dir) {
  494. if (dir == null) return false;
  495. // dir doesn't exist then return true
  496. if (!dir.exists()) return true;
  497. // dir isn't a directory then return false
  498. if (!dir.isDirectory()) return false;
  499. File[] files = dir.listFiles();
  500. if (files != null && files.length > 0) {
  501. for (File file : files) {
  502. if (file.isFile()) {
  503. if (!file.delete()) return false;
  504. } else if (file.isDirectory()) {
  505. if (!deleteDir(file)) return false;
  506. }
  507. }
  508. }
  509. return dir.delete();
  510. }
  511. /**
  512. * Delete the file.
  513. *
  514. * @param file The file.
  515. * @return {@code true}: success<br>{@code false}: fail
  516. */
  517. private static boolean deleteFile(final File file) {
  518. return file != null && (!file.exists() || file.isFile() && file.delete());
  519. }
  520. /**
  521. * 删除文件
  522. *
  523. * @param file
  524. */
  525. public static void deleteFile1(File file) {
  526. try {
  527. if (!file.exists()) {
  528. return;
  529. }
  530. if (file.isFile()) {
  531. file.delete();
  532. } else if (file.isDirectory()) {
  533. File files[] = file.listFiles();
  534. for (int i = 0; i < files.length; i++) {
  535. deleteFile(files[i]);
  536. }
  537. }
  538. file.delete();
  539. } catch (Exception e) {
  540. }
  541. }
  542. /**
  543. * Delete the all in directory.
  544. *
  545. * @param dirPath The path of directory.
  546. * @return {@code true}: success<br>{@code false}: fail
  547. */
  548. public static boolean deleteAllInDir(final String dirPath) {
  549. return deleteAllInDir(getFileByPath(dirPath));
  550. }
  551. /**
  552. * Delete the all in directory.
  553. *
  554. * @param dir The directory.
  555. * @return {@code true}: success<br>{@code false}: fail
  556. */
  557. public static boolean deleteAllInDir(final File dir) {
  558. return deleteFilesInDirWithFilter(dir, new FileFilter() {
  559. @Override
  560. public boolean accept(File pathname) {
  561. return true;
  562. }
  563. });
  564. }
  565. /**
  566. * Delete all files in directory.
  567. *
  568. * @param dirPath The path of directory.
  569. * @return {@code true}: success<br>{@code false}: fail
  570. */
  571. public static boolean deleteFilesInDir(final String dirPath) {
  572. return deleteFilesInDir(getFileByPath(dirPath));
  573. }
  574. /**
  575. * Delete all files in directory.
  576. *
  577. * @param dir The directory.
  578. * @return {@code true}: success<br>{@code false}: fail
  579. */
  580. public static boolean deleteFilesInDir(final File dir) {
  581. return deleteFilesInDirWithFilter(dir, new FileFilter() {
  582. @Override
  583. public boolean accept(File pathname) {
  584. return pathname.isFile();
  585. }
  586. });
  587. }
  588. /**
  589. * Delete all files that satisfy the filter in directory.
  590. *
  591. * @param dirPath The path of directory.
  592. * @param filter The filter.
  593. * @return {@code true}: success<br>{@code false}: fail
  594. */
  595. public static boolean deleteFilesInDirWithFilter(final String dirPath,
  596. final FileFilter filter) {
  597. return deleteFilesInDirWithFilter(getFileByPath(dirPath), filter);
  598. }
  599. /**
  600. * Delete all files that satisfy the filter in directory.
  601. *
  602. * @param dir The directory.
  603. * @param filter The filter.
  604. * @return {@code true}: success<br>{@code false}: fail
  605. */
  606. public static boolean deleteFilesInDirWithFilter(final File dir, final FileFilter filter) {
  607. if (dir == null || filter == null) return false;
  608. // dir doesn't exist then return true
  609. if (!dir.exists()) return true;
  610. // dir isn't a directory then return false
  611. if (!dir.isDirectory()) return false;
  612. File[] files = dir.listFiles();
  613. if (files != null && files.length != 0) {
  614. for (File file : files) {
  615. if (filter.accept(file)) {
  616. if (file.isFile()) {
  617. if (!file.delete()) return false;
  618. } else if (file.isDirectory()) {
  619. if (!deleteDir(file)) return false;
  620. }
  621. }
  622. }
  623. }
  624. return true;
  625. }
  626. /**
  627. * Return the files in directory.
  628. * <p>Doesn't traverse subdirectories</p>
  629. *
  630. * @param dirPath The path of directory.
  631. * @return the files in directory
  632. */
  633. public static List<File> listFilesInDir(final String dirPath) {
  634. return listFilesInDir(dirPath, null);
  635. }
  636. /**
  637. * Return the files in directory.
  638. * <p>Doesn't traverse subdirectories</p>
  639. *
  640. * @param dir The directory.
  641. * @return the files in directory
  642. */
  643. public static List<File> listFilesInDir(final File dir) {
  644. return listFilesInDir(dir, null);
  645. }
  646. /**
  647. * Return the files in directory.
  648. * <p>Doesn't traverse subdirectories</p>
  649. *
  650. * @param dirPath The path of directory.
  651. * @param comparator The comparator to determine the order of the list.
  652. * @return the files in directory
  653. */
  654. public static List<File> listFilesInDir(final String dirPath, Comparator<File> comparator) {
  655. return listFilesInDir(getFileByPath(dirPath), false, comparator);
  656. }
  657. /**
  658. * Return the files in directory.
  659. * <p>Doesn't traverse subdirectories</p>
  660. *
  661. * @param dir The directory.
  662. * @param comparator The comparator to determine the order of the list.
  663. * @return the files in directory
  664. */
  665. public static List<File> listFilesInDir(final File dir, Comparator<File> comparator) {
  666. return listFilesInDir(dir, false, comparator);
  667. }
  668. /**
  669. * Return the files in directory.
  670. *
  671. * @param dirPath The path of directory.
  672. * @param isRecursive True to traverse subdirectories, false otherwise.
  673. * @return the files in directory
  674. */
  675. public static List<File> listFilesInDir(final String dirPath, final boolean isRecursive) {
  676. return listFilesInDir(getFileByPath(dirPath), isRecursive);
  677. }
  678. /**
  679. * Return the files in directory.
  680. *
  681. * @param dir The directory.
  682. * @param isRecursive True to traverse subdirectories, false otherwise.
  683. * @return the files in directory
  684. */
  685. public static List<File> listFilesInDir(final File dir, final boolean isRecursive) {
  686. return listFilesInDir(dir, isRecursive, null);
  687. }
  688. /**
  689. * Return the files in directory.
  690. *
  691. * @param dirPath The path of directory.
  692. * @param isRecursive True to traverse subdirectories, false otherwise.
  693. * @param comparator The comparator to determine the order of the list.
  694. * @return the files in directory
  695. */
  696. public static List<File> listFilesInDir(final String dirPath,
  697. final boolean isRecursive,
  698. final Comparator<File> comparator) {
  699. return listFilesInDir(getFileByPath(dirPath), isRecursive, comparator);
  700. }
  701. /**
  702. * Return the files in directory.
  703. *
  704. * @param dir The directory.
  705. * @param isRecursive True to traverse subdirectories, false otherwise.
  706. * @param comparator The comparator to determine the order of the list.
  707. * @return the files in directory
  708. */
  709. public static List<File> listFilesInDir(final File dir,
  710. final boolean isRecursive,
  711. final Comparator<File> comparator) {
  712. return listFilesInDirWithFilter(dir, new FileFilter() {
  713. @Override
  714. public boolean accept(File pathname) {
  715. return true;
  716. }
  717. }, isRecursive, comparator);
  718. }
  719. /**
  720. * Return the files that satisfy the filter in directory.
  721. * <p>Doesn't traverse subdirectories</p>
  722. *
  723. * @param dirPath The path of directory.
  724. * @param filter The filter.
  725. * @return the files that satisfy the filter in directory
  726. */
  727. public static List<File> listFilesInDirWithFilter(final String dirPath,
  728. final FileFilter filter) {
  729. return listFilesInDirWithFilter(getFileByPath(dirPath), filter);
  730. }
  731. /**
  732. * Return the files that satisfy the filter in directory.
  733. * <p>Doesn't traverse subdirectories</p>
  734. *
  735. * @param dir The directory.
  736. * @param filter The filter.
  737. * @return the files that satisfy the filter in directory
  738. */
  739. public static List<File> listFilesInDirWithFilter(final File dir,
  740. final FileFilter filter) {
  741. return listFilesInDirWithFilter(dir, filter, false, null);
  742. }
  743. /**
  744. * Return the files that satisfy the filter in directory.
  745. * <p>Doesn't traverse subdirectories</p>
  746. *
  747. * @param dirPath The path of directory.
  748. * @param filter The filter.
  749. * @param comparator The comparator to determine the order of the list.
  750. * @return the files that satisfy the filter in directory
  751. */
  752. public static List<File> listFilesInDirWithFilter(final String dirPath,
  753. final FileFilter filter,
  754. final Comparator<File> comparator) {
  755. return listFilesInDirWithFilter(getFileByPath(dirPath), filter, comparator);
  756. }
  757. /**
  758. * Return the files that satisfy the filter in directory.
  759. * <p>Doesn't traverse subdirectories</p>
  760. *
  761. * @param dir The directory.
  762. * @param filter The filter.
  763. * @param comparator The comparator to determine the order of the list.
  764. * @return the files that satisfy the filter in directory
  765. */
  766. public static List<File> listFilesInDirWithFilter(final File dir,
  767. final FileFilter filter,
  768. final Comparator<File> comparator) {
  769. return listFilesInDirWithFilter(dir, filter, false, comparator);
  770. }
  771. /**
  772. * Return the files that satisfy the filter in directory.
  773. *
  774. * @param dirPath The path of directory.
  775. * @param filter The filter.
  776. * @param isRecursive True to traverse subdirectories, false otherwise.
  777. * @return the files that satisfy the filter in directory
  778. */
  779. public static List<File> listFilesInDirWithFilter(final String dirPath,
  780. final FileFilter filter,
  781. final boolean isRecursive) {
  782. return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive);
  783. }
  784. /**
  785. * Return the files that satisfy the filter in directory.
  786. *
  787. * @param dir The directory.
  788. * @param filter The filter.
  789. * @param isRecursive True to traverse subdirectories, false otherwise.
  790. * @return the files that satisfy the filter in directory
  791. */
  792. public static List<File> listFilesInDirWithFilter(final File dir,
  793. final FileFilter filter,
  794. final boolean isRecursive) {
  795. return listFilesInDirWithFilter(dir, filter, isRecursive, null);
  796. }
  797. /**
  798. * Return the files that satisfy the filter in directory.
  799. *
  800. * @param dirPath The path of directory.
  801. * @param filter The filter.
  802. * @param isRecursive True to traverse subdirectories, false otherwise.
  803. * @param comparator The comparator to determine the order of the list.
  804. * @return the files that satisfy the filter in directory
  805. */
  806. public static List<File> listFilesInDirWithFilter(final String dirPath,
  807. final FileFilter filter,
  808. final boolean isRecursive,
  809. final Comparator<File> comparator) {
  810. return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive, comparator);
  811. }
  812. /**
  813. * Return the files that satisfy the filter in directory.
  814. *
  815. * @param dir The directory.
  816. * @param filter The filter.
  817. * @param isRecursive True to traverse subdirectories, false otherwise.
  818. * @param comparator The comparator to determine the order of the list.
  819. * @return the files that satisfy the filter in directory
  820. */
  821. public static List<File> listFilesInDirWithFilter(final File dir,
  822. final FileFilter filter,
  823. final boolean isRecursive,
  824. final Comparator<File> comparator) {
  825. List<File> files = listFilesInDirWithFilterInner(dir, filter, isRecursive);
  826. if (comparator != null) {
  827. Collections.sort(files, comparator);
  828. }
  829. return files;
  830. }
  831. private static List<File> listFilesInDirWithFilterInner(final File dir,
  832. final FileFilter filter,
  833. final boolean isRecursive) {
  834. List<File> list = new ArrayList<>();
  835. if (!isDir(dir)) return list;
  836. File[] files = dir.listFiles();
  837. if (files != null && files.length > 0) {
  838. for (File file : files) {
  839. if (filter.accept(file)) {
  840. list.add(file);
  841. }
  842. if (isRecursive && file.isDirectory()) {
  843. list.addAll(listFilesInDirWithFilterInner(file, filter, true));
  844. }
  845. }
  846. }
  847. return list;
  848. }
  849. /**
  850. * Return the time that the file was last modified.
  851. *
  852. * @param filePath The path of file.
  853. * @return the time that the file was last modified
  854. */
  855. public static long getFileLastModified(final String filePath) {
  856. return getFileLastModified(getFileByPath(filePath));
  857. }
  858. /**
  859. * Return the time that the file was last modified.
  860. *
  861. * @param file The file.
  862. * @return the time that the file was last modified
  863. */
  864. public static long getFileLastModified(final File file) {
  865. if (file == null) return -1;
  866. return file.lastModified();
  867. }
  868. /**
  869. * Return the charset of file simply.
  870. *
  871. * @param filePath The path of file.
  872. * @return the charset of file simply
  873. */
  874. public static String getFileCharsetSimple(final String filePath) {
  875. return getFileCharsetSimple(getFileByPath(filePath));
  876. }
  877. /**
  878. * Return the charset of file simply.
  879. *
  880. * @param file The file.
  881. * @return the charset of file simply
  882. */
  883. public static String getFileCharsetSimple(final File file) {
  884. if (file == null) return "";
  885. if (isUtf8(file)) return "UTF-8";
  886. int p = 0;
  887. InputStream is = null;
  888. try {
  889. is = new BufferedInputStream(new FileInputStream(file));
  890. p = (is.read() << 8) + is.read();
  891. } catch (IOException e) {
  892. e.printStackTrace();
  893. } finally {
  894. try {
  895. if (is != null) {
  896. is.close();
  897. }
  898. } catch (IOException e) {
  899. e.printStackTrace();
  900. }
  901. }
  902. switch (p) {
  903. case 0xfffe:
  904. return "Unicode";
  905. case 0xfeff:
  906. return "UTF-16BE";
  907. default:
  908. return "GBK";
  909. }
  910. }
  911. /**
  912. * Return whether the charset of file is utf8.
  913. *
  914. * @param filePath The path of file.
  915. * @return {@code true}: yes<br>{@code false}: no
  916. */
  917. public static boolean isUtf8(final String filePath) {
  918. return isUtf8(getFileByPath(filePath));
  919. }
  920. /**
  921. * Return whether the charset of file is utf8.
  922. *
  923. * @param file The file.
  924. * @return {@code true}: yes<br>{@code false}: no
  925. */
  926. public static boolean isUtf8(final File file) {
  927. if (file == null) return false;
  928. InputStream is = null;
  929. try {
  930. byte[] bytes = new byte[24];
  931. is = new BufferedInputStream(new FileInputStream(file));
  932. int read = is.read(bytes);
  933. if (read != -1) {
  934. byte[] readArr = new byte[read];
  935. System.arraycopy(bytes, 0, readArr, 0, read);
  936. return isUtf8(readArr) == 100;
  937. } else {
  938. return false;
  939. }
  940. } catch (IOException e) {
  941. e.printStackTrace();
  942. } finally {
  943. try {
  944. if (is != null) {
  945. is.close();
  946. }
  947. } catch (IOException e) {
  948. e.printStackTrace();
  949. }
  950. }
  951. return false;
  952. }
  953. /**
  954. * UTF-8编码方式
  955. * ----------------------------------------------
  956. * 0xxxxxxx
  957. * 110xxxxx 10xxxxxx
  958. * 1110xxxx 10xxxxxx 10xxxxxx
  959. * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  960. */
  961. private static int isUtf8(byte[] raw) {
  962. int i, len;
  963. int utf8 = 0, ascii = 0;
  964. if (raw.length > 3) {
  965. if ((raw[0] == (byte) 0xEF) && (raw[1] == (byte) 0xBB) && (raw[2] == (byte) 0xBF)) {
  966. return 100;
  967. }
  968. }
  969. len = raw.length;
  970. int child = 0;
  971. for (i = 0; i < len; ) {
  972. // UTF-8 byte shouldn't be FF and FE
  973. if ((raw[i] & (byte) 0xFF) == (byte) 0xFF || (raw[i] & (byte) 0xFE) == (byte) 0xFE) {
  974. return 0;
  975. }
  976. if (child == 0) {
  977. // ASCII format is 0x0*******
  978. if ((raw[i] & (byte) 0x7F) == raw[i] && raw[i] != 0) {
  979. ascii++;
  980. } else if ((raw[i] & (byte) 0xC0) == (byte) 0xC0) {
  981. // 0x11****** maybe is UTF-8
  982. for (int bit = 0; bit < 8; bit++) {
  983. if ((((byte) (0x80 >> bit)) & raw[i]) == ((byte) (0x80 >> bit))) {
  984. child = bit;
  985. } else {
  986. break;
  987. }
  988. }
  989. utf8++;
  990. }
  991. i++;
  992. } else {
  993. child = (raw.length - i > child) ? child : (raw.length - i);
  994. boolean currentNotUtf8 = false;
  995. for (int children = 0; children < child; children++) {
  996. // format must is 0x10******
  997. if ((raw[i + children] & ((byte) 0x80)) != ((byte) 0x80)) {
  998. if ((raw[i + children] & (byte) 0x7F) == raw[i + children] && raw[i] != 0) {
  999. // ASCII format is 0x0*******
  1000. ascii++;
  1001. }
  1002. currentNotUtf8 = true;
  1003. }
  1004. }
  1005. if (currentNotUtf8) {
  1006. utf8--;
  1007. i++;
  1008. } else {
  1009. utf8 += child;
  1010. i += child;
  1011. }
  1012. child = 0;
  1013. }
  1014. }
  1015. // UTF-8 contains ASCII
  1016. if (ascii == len) {
  1017. return 100;
  1018. }
  1019. return (int) (100 * ((float) (utf8 + ascii) / (float) len));
  1020. }
  1021. /**
  1022. * Return the number of lines of file.
  1023. *
  1024. * @param filePath The path of file.
  1025. * @return the number of lines of file
  1026. */
  1027. public static int getFileLines(final String filePath) {
  1028. return getFileLines(getFileByPath(filePath));
  1029. }
  1030. /**
  1031. * Return the number of lines of file.
  1032. *
  1033. * @param file The file.
  1034. * @return the number of lines of file
  1035. */
  1036. public static int getFileLines(final File file) {
  1037. int count = 1;
  1038. InputStream is = null;
  1039. try {
  1040. is = new BufferedInputStream(new FileInputStream(file));
  1041. byte[] buffer = new byte[1024];
  1042. int readChars;
  1043. if (LINE_SEP.endsWith("\n")) {
  1044. while ((readChars = is.read(buffer, 0, 1024)) != -1) {
  1045. for (int i = 0; i < readChars; ++i) {
  1046. if (buffer[i] == '\n') ++count;
  1047. }
  1048. }
  1049. } else {
  1050. while ((readChars = is.read(buffer, 0, 1024)) != -1) {
  1051. for (int i = 0; i < readChars; ++i) {
  1052. if (buffer[i] == '\r') ++count;
  1053. }
  1054. }
  1055. }
  1056. } catch (IOException e) {
  1057. e.printStackTrace();
  1058. } finally {
  1059. try {
  1060. if (is != null) {
  1061. is.close();
  1062. }
  1063. } catch (IOException e) {
  1064. e.printStackTrace();
  1065. }
  1066. }
  1067. return count;
  1068. }
  1069. /**
  1070. * Return the size.
  1071. *
  1072. * @param filePath The path of file.
  1073. * @return the size
  1074. */
  1075. public static String getSize(final String filePath) {
  1076. return getSize(getFileByPath(filePath));
  1077. }
  1078. /**
  1079. * Return the size.
  1080. *
  1081. * @param file The directory.
  1082. * @return the size
  1083. */
  1084. public static String getSize(final File file) {
  1085. if (file == null) return "";
  1086. if (file.isDirectory()) {
  1087. return getDirSize(file);
  1088. }
  1089. return getFileSize(file);
  1090. }
  1091. /**
  1092. * Return the size of directory.
  1093. *
  1094. * @param dir The directory.
  1095. * @return the size of directory
  1096. */
  1097. private static String getDirSize(final File dir) {
  1098. long len = getDirLength(dir);
  1099. return len == -1 ? "" : UtilsBridge.byte2FitMemorySize(len);
  1100. }
  1101. /**
  1102. * Return the size of file.
  1103. *
  1104. * @param file The file.
  1105. * @return the length of file
  1106. */
  1107. private static String getFileSize(final File file) {
  1108. long len = getFileLength(file);
  1109. return len == -1 ? "" : UtilsBridge.byte2FitMemorySize(len);
  1110. }
  1111. /**
  1112. * Return the length.
  1113. *
  1114. * @param filePath The path of file.
  1115. * @return the length
  1116. */
  1117. public static long getLength(final String filePath) {
  1118. return getLength(getFileByPath(filePath));
  1119. }
  1120. /**
  1121. * Return the length.
  1122. *
  1123. * @param file The file.
  1124. * @return the length
  1125. */
  1126. public static long getLength(final File file) {
  1127. if (file == null) return 0;
  1128. if (file.isDirectory()) {
  1129. return getDirLength(file);
  1130. }
  1131. return getFileLength(file);
  1132. }
  1133. /**
  1134. * Return the length of directory.
  1135. *
  1136. * @param dir The directory.
  1137. * @return the length of directory
  1138. */
  1139. private static long getDirLength(final File dir) {
  1140. if (!isDir(dir)) return 0;
  1141. long len = 0;
  1142. File[] files = dir.listFiles();
  1143. if (files != null && files.length > 0) {
  1144. for (File file : files) {
  1145. if (file.isDirectory()) {
  1146. len += getDirLength(file);
  1147. } else {
  1148. len += file.length();
  1149. }
  1150. }
  1151. }
  1152. return len;
  1153. }
  1154. /**
  1155. * Return the length of file.
  1156. *
  1157. * @param filePath The path of file.
  1158. * @return the length of file
  1159. */
  1160. public static long getFileLength(final String filePath) {
  1161. boolean isURL = filePath.matches("[a-zA-z]+://[^\\s]*");
  1162. if (isURL) {
  1163. try {
  1164. HttpsURLConnection conn = (HttpsURLConnection) new URL(filePath).openConnection();
  1165. conn.setRequestProperty("Accept-Encoding", "identity");
  1166. conn.connect();
  1167. if (conn.getResponseCode() == 200) {
  1168. return conn.getContentLength();
  1169. }
  1170. return -1;
  1171. } catch (IOException e) {
  1172. e.printStackTrace();
  1173. }
  1174. }
  1175. return getFileLength(getFileByPath(filePath));
  1176. }
  1177. /**
  1178. * Return the length of file.
  1179. *
  1180. * @param file The file.
  1181. * @return the length of file
  1182. */
  1183. private static long getFileLength(final File file) {
  1184. if (!isFile(file)) return -1;
  1185. return file.length();
  1186. }
  1187. /**
  1188. * Return the MD5 of file.
  1189. *
  1190. * @param filePath The path of file.
  1191. * @return the md5 of file
  1192. */
  1193. public static String getFileMD5ToString(final String filePath) {
  1194. File file = UtilsBridge.isSpace(filePath) ? null : new File(filePath);
  1195. return getFileMD5ToString(file);
  1196. }
  1197. /**
  1198. * Return the MD5 of file.
  1199. *
  1200. * @param file The file.
  1201. * @return the md5 of file
  1202. */
  1203. public static String getFileMD5ToString(final File file) {
  1204. return UtilsBridge.bytes2HexString(getFileMD5(file));
  1205. }
  1206. /**
  1207. * Return the MD5 of file.
  1208. *
  1209. * @param filePath The path of file.
  1210. * @return the md5 of file
  1211. */
  1212. public static byte[] getFileMD5(final String filePath) {
  1213. return getFileMD5(getFileByPath(filePath));
  1214. }
  1215. /**
  1216. * Return the MD5 of file.
  1217. *
  1218. * @param file The file.
  1219. * @return the md5 of file
  1220. */
  1221. public static byte[] getFileMD5(final File file) {
  1222. if (file == null) return null;
  1223. DigestInputStream dis = null;
  1224. try {
  1225. FileInputStream fis = new FileInputStream(file);
  1226. MessageDigest md = MessageDigest.getInstance("MD5");
  1227. dis = new DigestInputStream(fis, md);
  1228. byte[] buffer = new byte[1024 * 256];
  1229. while (true) {
  1230. if (!(dis.read(buffer) > 0)) break;
  1231. }
  1232. md = dis.getMessageDigest();
  1233. return md.digest();
  1234. } catch (NoSuchAlgorithmException | IOException e) {
  1235. e.printStackTrace();
  1236. } finally {
  1237. try {
  1238. if (dis != null) {
  1239. dis.close();
  1240. }
  1241. } catch (IOException e) {
  1242. e.printStackTrace();
  1243. }
  1244. }
  1245. return null;
  1246. }
  1247. /**
  1248. * Return the file's path of directory.
  1249. *
  1250. * @param file The file.
  1251. * @return the file's path of directory
  1252. */
  1253. public static String getDirName(final File file) {
  1254. if (file == null) return "";
  1255. return getDirName(file.getAbsolutePath());
  1256. }
  1257. /**
  1258. * Return the file's path of directory.
  1259. *
  1260. * @param filePath The path of file.
  1261. * @return the file's path of directory
  1262. */
  1263. public static String getDirName(final String filePath) {
  1264. if (UtilsBridge.isSpace(filePath)) return "";
  1265. int lastSep = filePath.lastIndexOf(File.separator);
  1266. return lastSep == -1 ? "" : filePath.substring(0, lastSep + 1);
  1267. }
  1268. /**
  1269. * Return the name of file.
  1270. *
  1271. * @param file The file.
  1272. * @return the name of file
  1273. */
  1274. public static String getFileName(final File file) {
  1275. if (file == null) return "";
  1276. return getFileName(file.getAbsolutePath());
  1277. }
  1278. /**
  1279. * Return the name of file.
  1280. *
  1281. * @param filePath The path of file.
  1282. * @return the name of file
  1283. */
  1284. public static String getFileName(final String filePath) {
  1285. if (UtilsBridge.isSpace(filePath)) return "";
  1286. int lastSep = filePath.lastIndexOf(File.separator);
  1287. return lastSep == -1 ? filePath : filePath.substring(lastSep + 1);
  1288. }
  1289. /**
  1290. * Return the name of file without extension.
  1291. *
  1292. * @param file The file.
  1293. * @return the name of file without extension
  1294. */
  1295. public static String getFileNameNoExtension(final File file) {
  1296. if (file == null) return "";
  1297. return getFileNameNoExtension(file.getPath());
  1298. }
  1299. /**
  1300. * Return the name of file without extension.
  1301. *
  1302. * @param filePath The path of file.
  1303. * @return the name of file without extension
  1304. */
  1305. public static String getFileNameNoExtension(final String filePath) {
  1306. if (UtilsBridge.isSpace(filePath)) return "";
  1307. int lastPoi = filePath.lastIndexOf('.');
  1308. int lastSep = filePath.lastIndexOf(File.separator);
  1309. if (lastSep == -1) {
  1310. return (lastPoi == -1 ? filePath : filePath.substring(0, lastPoi));
  1311. }
  1312. if (lastPoi == -1 || lastSep > lastPoi) {
  1313. return filePath.substring(lastSep + 1);
  1314. }
  1315. return filePath.substring(lastSep + 1, lastPoi);
  1316. }
  1317. /**
  1318. * Return the extension of file.
  1319. *
  1320. * @param file The file.
  1321. * @return the extension of file
  1322. */
  1323. public static String getFileExtension(final File file) {
  1324. if (file == null) return "";
  1325. return getFileExtension(file.getPath());
  1326. }
  1327. /**
  1328. * Return the extension of file.
  1329. *
  1330. * @param filePath The path of file.
  1331. * @return the extension of file
  1332. */
  1333. public static String getFileExtension(final String filePath) {
  1334. if (UtilsBridge.isSpace(filePath)) return "";
  1335. int lastPoi = filePath.lastIndexOf('.');
  1336. int lastSep = filePath.lastIndexOf(File.separator);
  1337. if (lastPoi == -1 || lastSep >= lastPoi) return "";
  1338. return filePath.substring(lastPoi + 1);
  1339. }
  1340. /**
  1341. * Notify system to scan the file.
  1342. *
  1343. * @param filePath The path of file.
  1344. */
  1345. public static void notifySystemToScan(final String filePath) {
  1346. notifySystemToScan(getFileByPath(filePath));
  1347. }
  1348. /**
  1349. * Notify system to scan the file.
  1350. *
  1351. * @param file The file.
  1352. */
  1353. public static void notifySystemToScan(final File file) {
  1354. if (file == null || !file.exists()) return;
  1355. Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
  1356. intent.setData(Uri.parse("file://" + file.getAbsolutePath()));
  1357. Utils.getApp().sendBroadcast(intent);
  1358. }
  1359. /**
  1360. * Return the total size of file system.
  1361. *
  1362. * @param anyPathInFs Any path in file system.
  1363. * @return the total size of file system
  1364. */
  1365. public static long getFsTotalSize(String anyPathInFs) {
  1366. if (TextUtils.isEmpty(anyPathInFs)) return 0;
  1367. StatFs statFs = new StatFs(anyPathInFs);
  1368. long blockSize;
  1369. long totalSize;
  1370. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
  1371. blockSize = statFs.getBlockSizeLong();
  1372. totalSize = statFs.getBlockCountLong();
  1373. } else {
  1374. blockSize = statFs.getBlockSize();
  1375. totalSize = statFs.getBlockCount();
  1376. }
  1377. return blockSize * totalSize;
  1378. }
  1379. /**
  1380. * Return the available size of file system.
  1381. *
  1382. * @param anyPathInFs Any path in file system.
  1383. * @return the available size of file system
  1384. */
  1385. public static long getFsAvailableSize(final String anyPathInFs) {
  1386. if (TextUtils.isEmpty(anyPathInFs)) return 0;
  1387. StatFs statFs = new StatFs(anyPathInFs);
  1388. long blockSize;
  1389. long availableSize;
  1390. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
  1391. blockSize = statFs.getBlockSizeLong();
  1392. availableSize = statFs.getAvailableBlocksLong();
  1393. } else {
  1394. blockSize = statFs.getBlockSize();
  1395. availableSize = statFs.getAvailableBlocks();
  1396. }
  1397. return blockSize * availableSize;
  1398. }
  1399. ///////////////////////////////////////////////////////////////////////////
  1400. // interface
  1401. ///////////////////////////////////////////////////////////////////////////
  1402. public interface OnReplaceListener {
  1403. boolean onReplace(File srcFile, File destFile);
  1404. }
  1405. public static boolean writeFileToSDCard(ResponseBody body, String filePath, String fileName) {
  1406. if (null == body) {
  1407. return false;
  1408. }
  1409. try {
  1410. File futureStudioIconFile = new File(filePath + File.separator + fileName);
  1411. InputStream inputStream = null;
  1412. OutputStream outputStream = null;
  1413. try {
  1414. byte[] fileReader = new byte[4096];
  1415. long fileSize = body.contentLength();
  1416. long fileSizeDownloaded = 0;
  1417. inputStream = body.byteStream();
  1418. outputStream = new FileOutputStream(futureStudioIconFile);
  1419. while (true) {
  1420. int read = inputStream.read(fileReader);
  1421. if (read == -1) {
  1422. break;
  1423. }
  1424. outputStream.write(fileReader, 0, read);
  1425. fileSizeDownloaded += read;
  1426. }
  1427. outputStream.flush();
  1428. return true;
  1429. } catch (IOException e) {
  1430. return false;
  1431. } finally {
  1432. if (inputStream != null) {
  1433. inputStream.close();
  1434. }
  1435. if (outputStream != null) {
  1436. outputStream.close();
  1437. }
  1438. }
  1439. } catch (IOException e) {
  1440. return false;
  1441. }
  1442. }
  1443. public static String getFilePath(Bitmap bitmap) {
  1444. LogUtils.i("pq", "getFilePath bitmap:" + bitmap);
  1445. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  1446. bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);
  1447. String path = FileUtils.getCacheDir(Utils.getApp(), FileUtils.filesDirectory) + "/WhiteBroad";
  1448. LogUtils.i("pq", "path:" + path);
  1449. File dir = new File(path);
  1450. if (!dir.exists()) {
  1451. dir.mkdirs();
  1452. }
  1453. File file = new File(dir, System.currentTimeMillis() + ".png");
  1454. // File file = new File(path + "/" + System.currentTimeMillis() + ".png");
  1455. try {
  1456. createOrExistsFile(file);
  1457. FileOutputStream fos = new FileOutputStream(file);
  1458. InputStream is = new ByteArrayInputStream(baos.toByteArray());
  1459. int x = 0;
  1460. byte[] b = new byte[1024 * 100];
  1461. while ((x = is.read(b)) != -1) {
  1462. fos.write(b, 0, x);
  1463. }
  1464. fos.close();
  1465. } catch (Exception e) {
  1466. LogUtils.i("pq", "Exception:" + e.getMessage());
  1467. e.printStackTrace();
  1468. }
  1469. LogUtils.i("pq", "file path:" + file.getPath());
  1470. return file.getPath();
  1471. }
  1472. public static String getCacheDir(Context context, String directory) {
  1473. String fileDir;
  1474. try {
  1475. File file = new File(context.getExternalCacheDir() + File.separator + directory);
  1476. if (!file.exists()) {
  1477. file.mkdirs();
  1478. }
  1479. fileDir = file.getAbsolutePath();
  1480. return fileDir;
  1481. } catch (Exception e) {
  1482. return "";
  1483. }
  1484. }
  1485. public static String getCacheDir2(Context context, String directory) {
  1486. String fileDir;
  1487. try {
  1488. File file = new File(context.getCacheDir() + File.separator + directory);
  1489. if (!file.exists()) {
  1490. file.mkdirs();
  1491. }
  1492. fileDir = file.getAbsolutePath();
  1493. return fileDir;
  1494. } catch (Exception e) {
  1495. return "";
  1496. }
  1497. }
  1498. /**
  1499. * 判断SD卡上的文件是否存在
  1500. */
  1501. public static boolean isFileExist(String fileName) {
  1502. File file = new File(fileName);
  1503. return file == null ? false : file.exists();
  1504. }
  1505. /**
  1506. * 获取本地文件
  1507. *
  1508. * @param uri
  1509. * @param context
  1510. * @return
  1511. */
  1512. public static String getFilePathForN(Uri uri, Context context) {
  1513. Uri returnUri = uri;
  1514. Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
  1515. int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
  1516. int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
  1517. returnCursor.moveToFirst();
  1518. String name = (returnCursor.getString(nameIndex));
  1519. String size = (Long.toString(returnCursor.getLong(sizeIndex)));
  1520. File file = new File(context.getFilesDir(), name);
  1521. try {
  1522. InputStream inputStream = context.getContentResolver().openInputStream(uri);
  1523. FileOutputStream outputStream = new FileOutputStream(file);
  1524. int read = 0;
  1525. int maxBufferSize = 1 * 1024 * 1024;
  1526. int bytesAvailable = inputStream.available();
  1527. //int bufferSize = 1024;
  1528. int bufferSize = Math.min(bytesAvailable, maxBufferSize);
  1529. final byte[] buffers = new byte[bufferSize];
  1530. while ((read = inputStream.read(buffers)) != -1) {
  1531. outputStream.write(buffers, 0, read);
  1532. }
  1533. Log.e("File Size", "Size " + file.length());
  1534. inputStream.close();
  1535. outputStream.close();
  1536. Log.e("File Path", "Path " + file.getPath());
  1537. Log.e("File Size", "Size " + file.length());
  1538. } catch (Exception e) {
  1539. Log.e("Exception", e.getMessage());
  1540. }
  1541. return file.getPath();
  1542. }
  1543. public static File saveBase64ImgToLocalFile(String base64) throws Exception {
  1544. byte[] bytes;
  1545. if (base64.startsWith("data:image/png;base64")) {
  1546. String[] split = base64.split(",");
  1547. bytes = Base64.decode(split[1], Base64.DEFAULT);
  1548. } else {
  1549. bytes = Base64.decode(base64, Base64.DEFAULT);
  1550. }
  1551. Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  1552. File parentFile = new File(FileUtils.getCacheDir(Utils.getApp()) + File.separator + "img");
  1553. if (!parentFile.exists()) {
  1554. parentFile.mkdirs();
  1555. }
  1556. String targetFileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()) + ".png";
  1557. File file = new File(parentFile, targetFileName);
  1558. FileUtils.saveImag(bitmap, file.getAbsolutePath());
  1559. if (file != null && file.exists()) {
  1560. try {
  1561. MediaStore.Images.Media.insertImage(Utils.getApp().getContentResolver(),
  1562. file.getAbsolutePath(), file.getName(), null);
  1563. // 最后通知图库更新
  1564. Utils.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
  1565. Uri.fromFile(new File(file.getPath()))));
  1566. } catch (FileNotFoundException e) {
  1567. e.printStackTrace();
  1568. }
  1569. }
  1570. return new File(file.getAbsolutePath());
  1571. }
  1572. /**
  1573. * 保存图片
  1574. *
  1575. * @param bmp
  1576. */
  1577. public static void saveImag(Bitmap bmp, String path) throws Exception {
  1578. // 首先保存图片
  1579. File file = new File(path);
  1580. FileOutputStream fos = new FileOutputStream(file);
  1581. bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
  1582. fos.flush();
  1583. fos.close();
  1584. }
  1585. /**
  1586. * 将assets中的sf2文件保存到sd卡供midi使用
  1587. *
  1588. * @param application
  1589. */
  1590. public static void CopyMidiFile(Application application) {
  1591. try {
  1592. File f = new File(getCacheDir(application,"colexiu") + "/dysf.sf2");
  1593. if (f.exists()) {
  1594. if (f.length() < 1024 * 1024 * 38) {
  1595. //如果文件存在,并且低于38M
  1596. //目前没有md5校验,所以先这样处理文件完整性的问题
  1597. f.delete();
  1598. }
  1599. }
  1600. if (!f.exists()) {
  1601. InputStream is = application.getAssets().open("soundfont.sf2");
  1602. if (is == null) {
  1603. return;
  1604. }
  1605. f.createNewFile();
  1606. OutputStream os = new FileOutputStream(f);
  1607. byte[] data = new byte[1024];
  1608. int len = 0;
  1609. while ((len = is.read(data)) != -1) {
  1610. os.write(data, 0, len);
  1611. }
  1612. is.close();
  1613. os.close();
  1614. }
  1615. } catch (IOException e) {
  1616. // TODO Auto-generated catch block
  1617. e.printStackTrace();
  1618. }
  1619. }
  1620. /**
  1621. * 保存图片到图库
  1622. *
  1623. * @param bmp
  1624. */
  1625. public static void saveImageToLocal(Bitmap bmp, String path) {
  1626. // 首先保存图片
  1627. File file = new File(path);
  1628. try {
  1629. FileOutputStream fos = new FileOutputStream(file);
  1630. bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
  1631. fos.flush();
  1632. fos.close();
  1633. } catch (FileNotFoundException e) {
  1634. e.printStackTrace();
  1635. } catch (IOException e) {
  1636. e.printStackTrace();
  1637. }
  1638. }
  1639. public static File saveImgToLocalFile(Bitmap bitmap) {
  1640. File parentFile = new File(FileUtils.getCacheDir(Utils.getApp()) + File.separator + "share");
  1641. if (!parentFile.exists()) {
  1642. parentFile.mkdirs();
  1643. }
  1644. String targetFileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()) + ".png";
  1645. File file = new File(parentFile, targetFileName);
  1646. saveImageToLocalForJPEG(bitmap, file.getAbsolutePath());
  1647. return new File(file.getAbsolutePath());
  1648. }
  1649. /**
  1650. * 保存图片到图库
  1651. *
  1652. * @param bmp
  1653. */
  1654. public static void saveImageToLocalForJPEG(Bitmap bmp, String path) {
  1655. // 首先保存图片
  1656. File file = new File(path);
  1657. try {
  1658. FileOutputStream fos = new FileOutputStream(file);
  1659. bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
  1660. fos.flush();
  1661. fos.close();
  1662. } catch (FileNotFoundException e) {
  1663. e.printStackTrace();
  1664. } catch (IOException e) {
  1665. e.printStackTrace();
  1666. }
  1667. }
  1668. public static String getCompressPath() {
  1669. String compressPath = getCacheDir(Utils.getApp()) + File.separator + "compress";
  1670. File file = new File(compressPath);
  1671. if (!file.exists()) {
  1672. file.mkdirs();
  1673. }
  1674. return compressPath;
  1675. }
  1676. public static boolean isMatchTargetFileType(String targetType, String filePath) {
  1677. try {
  1678. Log.i("FileUtils", "filePath:" + filePath);
  1679. if (TextUtils.isEmpty(targetType)) {
  1680. Log.i("FileUtils", "targetType is null");
  1681. return true;
  1682. }
  1683. if (TextUtils.equals(targetType, "video") || TextUtils.equals(targetType, "img")) {
  1684. //忽略video或者img格式
  1685. Log.i("FileUtils", "video or img type is ignore");
  1686. return true;
  1687. }
  1688. File file = new File(filePath);
  1689. if (!file.exists()) {
  1690. Log.i("FileUtils", "file is not exist");
  1691. return false;
  1692. }
  1693. int lastDot = file.getName().lastIndexOf(".");
  1694. if (lastDot < 0) {
  1695. Log.i("FileUtils", "lastDot is 0 isEmpty filetype");
  1696. return false;
  1697. }
  1698. String type = file.getName().substring(lastDot + 1).toLowerCase();
  1699. if (TextUtils.isEmpty(type)) {
  1700. Log.i("FileUtils", "isEmpty filetype");
  1701. return false;
  1702. }
  1703. if (TextUtils.equals(targetType, "midi")) {
  1704. //兼容下mid格式
  1705. return TextUtils.equals(type, "midi") || TextUtils.equals(type, "mid");
  1706. }
  1707. Log.i("FileUtils", "targetType:" + targetType + "-type:" + type);
  1708. return TextUtils.equals(targetType, type);
  1709. } catch (Exception e) {
  1710. e.printStackTrace();
  1711. }
  1712. return true;
  1713. }
  1714. public static boolean saveAudioToMusic(Context context, String filePath) {
  1715. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
  1716. return saveAudioToMusicBeforeQ(context, filePath);
  1717. } else {
  1718. return saveAudioToMusicAfterQ(context, filePath);
  1719. }
  1720. }
  1721. /**
  1722. * 获取视频的contentValue
  1723. */
  1724. public static ContentValues getAudioContentValues(Context context, File paramFile, long timestamp) {
  1725. ContentValues localContentValues = new ContentValues();
  1726. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
  1727. localContentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM
  1728. + File.separator + context.getPackageName());
  1729. }
  1730. localContentValues.put(MediaStore.Audio.Media.TITLE, paramFile.getName());
  1731. localContentValues.put(MediaStore.Audio.Media.DISPLAY_NAME, paramFile.getName());
  1732. localContentValues.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3");
  1733. localContentValues.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/yyszkt");
  1734. localContentValues.put(MediaStore.Audio.Media.DATE_TAKEN, timestamp);
  1735. localContentValues.put(MediaStore.Audio.Media.DATE_MODIFIED, timestamp);
  1736. localContentValues.put(MediaStore.Audio.Media.DATE_ADDED, timestamp);
  1737. localContentValues.put(MediaStore.Audio.Media.SIZE, paramFile.length());
  1738. localContentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
  1739. localContentValues.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
  1740. localContentValues.put(MediaStore.Audio.Media.IS_ALARM, false);
  1741. localContentValues.put(MediaStore.Audio.Media.IS_MUSIC, false);
  1742. return localContentValues;
  1743. }
  1744. private static boolean saveAudioToMusicAfterQ(Context context, String audioFilePath) {
  1745. try {
  1746. ContentResolver contentResolver = context.getContentResolver();
  1747. File tempFile = new File(audioFilePath);
  1748. ContentValues contentValues = getAudioContentValues(context, tempFile, System.currentTimeMillis());
  1749. Uri uri = contentResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, contentValues);
  1750. copyFileAfterQ(context, contentResolver, tempFile, uri);
  1751. contentValues.clear();
  1752. contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
  1753. context.getContentResolver().update(uri, contentValues, null, null);
  1754. context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
  1755. return true;
  1756. } catch (Exception e) {
  1757. e.printStackTrace();
  1758. return false;
  1759. }
  1760. }
  1761. private static boolean saveAudioToMusicBeforeQ(Context context, String audioFile) {
  1762. File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
  1763. File tempFile = new File(audioFile);
  1764. File destFile = new File(picDir, "yyszkt" + File.separator + tempFile.getName());
  1765. FileInputStream ins = null;
  1766. BufferedOutputStream ous = null;
  1767. try {
  1768. ins = new FileInputStream(tempFile);
  1769. ous = new BufferedOutputStream(new FileOutputStream(destFile));
  1770. long nread = 0L;
  1771. byte[] buf = new byte[1024];
  1772. int n;
  1773. while ((n = ins.read(buf)) > 0) {
  1774. ous.write(buf, 0, n);
  1775. nread += n;
  1776. }
  1777. MediaScannerConnection.scanFile(
  1778. context,
  1779. new String[]{destFile.getAbsolutePath()},
  1780. new String[]{"audio/*"},
  1781. (path, uri) -> {
  1782. // Scan Completed
  1783. });
  1784. return true;
  1785. } catch (Exception e) {
  1786. e.printStackTrace();
  1787. return false;
  1788. } finally {
  1789. try {
  1790. if (ins != null) {
  1791. ins.close();
  1792. }
  1793. if (ous != null) {
  1794. ous.close();
  1795. }
  1796. } catch (IOException e) {
  1797. e.printStackTrace();
  1798. }
  1799. }
  1800. }
  1801. public static boolean saveVideoToGallery(Context context, String filePath) {
  1802. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
  1803. return saveVideoToAlbumBeforeQ(context, filePath);
  1804. } else {
  1805. return saveVideoToAlbumAfterQ(context, filePath);
  1806. }
  1807. }
  1808. private static boolean saveVideoToAlbumAfterQ(Context context, String videoFile) {
  1809. try {
  1810. ContentResolver contentResolver = context.getContentResolver();
  1811. File tempFile = new File(videoFile);
  1812. ContentValues contentValues = getVideoContentValues(context, tempFile, System.currentTimeMillis());
  1813. Uri uri = contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
  1814. copyFileAfterQ(context, contentResolver, tempFile, uri);
  1815. contentValues.clear();
  1816. contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
  1817. context.getContentResolver().update(uri, contentValues, null, null);
  1818. context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
  1819. return true;
  1820. } catch (Exception e) {
  1821. e.printStackTrace();
  1822. return false;
  1823. }
  1824. }
  1825. /**
  1826. * 获取视频的contentValue
  1827. */
  1828. public static ContentValues getVideoContentValues(Context context, File paramFile, long timestamp) {
  1829. ContentValues localContentValues = new ContentValues();
  1830. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
  1831. localContentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM
  1832. + File.separator + context.getPackageName());
  1833. }
  1834. localContentValues.put(MediaStore.Video.Media.TITLE, paramFile.getName());
  1835. localContentValues.put(MediaStore.Video.Media.DISPLAY_NAME, paramFile.getName());
  1836. localContentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
  1837. localContentValues.put(MediaStore.Video.Media.DATE_TAKEN, timestamp);
  1838. localContentValues.put(MediaStore.Video.Media.DATE_MODIFIED, timestamp);
  1839. localContentValues.put(MediaStore.Video.Media.DATE_ADDED, timestamp);
  1840. localContentValues.put(MediaStore.Video.Media.SIZE, paramFile.length());
  1841. return localContentValues;
  1842. }
  1843. private static void copyFileAfterQ(Context context, ContentResolver localContentResolver, File tempFile, Uri localUri) throws IOException {
  1844. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
  1845. context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.Q) {
  1846. //拷贝文件到相册的uri,android10及以上得这么干,否则不会显示。可以参考ScreenMediaRecorder的save方法
  1847. OutputStream os = localContentResolver.openOutputStream(localUri);
  1848. Files.copy(tempFile.toPath(), os);
  1849. os.close();
  1850. // tempFile.delete();
  1851. }
  1852. }
  1853. private static boolean saveVideoToAlbumBeforeQ(Context context, String videoFile) {
  1854. File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
  1855. File tempFile = new File(videoFile);
  1856. File destFile = new File(picDir, context.getPackageName() + File.separator + tempFile.getName());
  1857. FileInputStream ins = null;
  1858. BufferedOutputStream ous = null;
  1859. try {
  1860. ins = new FileInputStream(tempFile);
  1861. ous = new BufferedOutputStream(new FileOutputStream(destFile));
  1862. long nread = 0L;
  1863. byte[] buf = new byte[1024];
  1864. int n;
  1865. while ((n = ins.read(buf)) > 0) {
  1866. ous.write(buf, 0, n);
  1867. nread += n;
  1868. }
  1869. MediaScannerConnection.scanFile(
  1870. context,
  1871. new String[]{destFile.getAbsolutePath()},
  1872. new String[]{"video/*"},
  1873. (path, uri) -> {
  1874. // Scan Completed
  1875. });
  1876. return true;
  1877. } catch (Exception e) {
  1878. e.printStackTrace();
  1879. return false;
  1880. } finally {
  1881. try {
  1882. if (ins != null) {
  1883. ins.close();
  1884. }
  1885. if (ous != null) {
  1886. ous.close();
  1887. }
  1888. } catch (IOException e) {
  1889. e.printStackTrace();
  1890. }
  1891. }
  1892. }
  1893. /**
  1894. * 删除文件
  1895. *
  1896. * @param path
  1897. */
  1898. public static void deleteFile(String path) {
  1899. if (TextUtils.isEmpty(path)) {
  1900. return;
  1901. }
  1902. File file = new File(path);
  1903. deleteFile(file);
  1904. }
  1905. /**
  1906. * 获取文件后缀类型根据url
  1907. * @param url
  1908. * @return
  1909. */
  1910. public static String getFileTypeFromUrl(String url) {
  1911. try {
  1912. URL url1 =new URL(url);
  1913. String path = url1.getPath();
  1914. if (path.contains("?")) {
  1915. String[] split = path.split("\\?");
  1916. path = split[0];
  1917. }
  1918. int lastDot = path.lastIndexOf(".");
  1919. if (lastDot < 0) {
  1920. return "";
  1921. }
  1922. String type = path.substring(lastDot + 1).toLowerCase();
  1923. return type;
  1924. } catch (Exception e) {
  1925. e.printStackTrace();
  1926. }
  1927. return "";
  1928. }
  1929. public static boolean clearMusicMergeCache() {
  1930. try {
  1931. String material = FileUtils.getCacheDir(Utils.getApp(), "musicmerge");
  1932. FileUtils.deleteAllInDir(material);
  1933. return true;
  1934. } catch (Exception e) {
  1935. e.printStackTrace();
  1936. }
  1937. return false;
  1938. }
  1939. }