MyFileUtils.java 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  1. package com.cooleshow.base.utils;
  2. import static android.os.Environment.DIRECTORY_DOWNLOADS;
  3. import android.annotation.SuppressLint;
  4. import android.content.ContentUris;
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.database.Cursor;
  8. import android.graphics.Bitmap;
  9. import android.graphics.BitmapFactory;
  10. import android.graphics.Matrix;
  11. import android.net.Uri;
  12. import android.os.Build;
  13. import android.os.Environment;
  14. import android.provider.DocumentsContract;
  15. import android.provider.MediaStore;
  16. import android.provider.OpenableColumns;
  17. import android.text.TextUtils;
  18. import android.util.Base64;
  19. import android.util.Log;
  20. import androidx.annotation.NonNull;
  21. import androidx.annotation.Nullable;
  22. import androidx.core.content.FileProvider;
  23. import java.io.BufferedOutputStream;
  24. import java.io.BufferedReader;
  25. import java.io.ByteArrayInputStream;
  26. import java.io.ByteArrayOutputStream;
  27. import java.io.File;
  28. import java.io.FileInputStream;
  29. import java.io.FileNotFoundException;
  30. import java.io.FileOutputStream;
  31. import java.io.FileReader;
  32. import java.io.IOException;
  33. import java.io.InputStream;
  34. import java.io.LineNumberReader;
  35. import java.io.OutputStream;
  36. import java.text.DecimalFormat;
  37. import java.util.ArrayList;
  38. import java.util.HashMap;
  39. import java.util.List;
  40. import java.util.Map;
  41. import okhttp3.ResponseBody;
  42. /**
  43. * Description:
  44. * Copyright : Copyright (c) 2019
  45. * Company : 大雅乐盟
  46. * Author : r
  47. * Date : 2019/9/6 15:07
  48. */
  49. public class MyFileUtils {
  50. private static final String TAG = "FileUtil";
  51. private static final String filesDirectory = getCacheDir(Utils.getApp())+ File.separator+"cooleshow";
  52. public static final String examDownloadDirectory = "examDownload";
  53. public static String getCacheDir(Context context) {
  54. String cacheDir = context.getExternalCacheDir().getAbsolutePath();
  55. return cacheDir;
  56. }
  57. public static String getCacheDir(Context context, String directory) {
  58. String fileDir;
  59. try {
  60. File file = new File(context.getExternalCacheDir() + File.separator + directory);
  61. if (!file.exists()) {
  62. file.mkdirs();
  63. }
  64. fileDir = file.getAbsolutePath();
  65. return fileDir;
  66. } catch (Exception e) {
  67. return "";
  68. }
  69. }
  70. public static String getFilesDir(Context context) {
  71. try {
  72. File file = context.getExternalFilesDir(filesDirectory);
  73. if (!file.exists()) {
  74. file.mkdirs();
  75. }
  76. String fileDir = file.getAbsolutePath();
  77. return fileDir;
  78. } catch (Exception e) {
  79. return "";
  80. }
  81. }
  82. public static String getFilesDir(Context context, String directory) {
  83. try {
  84. File file = context.getExternalFilesDir(filesDirectory + File.separator + directory);
  85. if (!file.exists()) {
  86. file.mkdirs();
  87. }
  88. String fileDir = file.getAbsolutePath();
  89. return fileDir;
  90. } catch (Exception e) {
  91. return "";
  92. }
  93. }
  94. public static String getPublicDirectory(String path) {
  95. String fileDir = null;
  96. try {
  97. File file = new File(filesDirectory);
  98. if (!file.exists()) {
  99. file.mkdirs();
  100. }
  101. fileDir = file.getAbsolutePath();
  102. if (!TextUtils.isEmpty(path)) {
  103. File filePath = new File(file.getPath() + File.separator + path);
  104. if (!filePath.exists()) {
  105. filePath.mkdirs();
  106. }
  107. fileDir = filePath.getAbsolutePath();
  108. }
  109. return fileDir;
  110. } catch (Exception e) {
  111. e.printStackTrace();
  112. return "";
  113. }
  114. }
  115. public static String getPublicDirectoryDownload() {
  116. try {
  117. File file = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS);
  118. return file.getAbsolutePath();
  119. } catch (Exception e) {
  120. return "";
  121. }
  122. }
  123. /**
  124. * 获取该路径下全部的文件名
  125. *
  126. * @param path
  127. * @return
  128. */
  129. public static List<String> getFilesAllName(String path) {
  130. File file = new File(path);
  131. File[] files = file.listFiles();
  132. if (files == null) {
  133. Log.e("error", "空目录");
  134. return null;
  135. }
  136. List<String> s = new ArrayList<>();
  137. for (int i = 0; i < files.length; i++) {
  138. s.add(files[i].getAbsolutePath());
  139. }
  140. return s;
  141. }
  142. /**
  143. * 根据文件后缀名判断是否是图片(不一定准确)
  144. *
  145. * @param path
  146. * @return
  147. */
  148. public static boolean isImg(String path) {
  149. try {
  150. File file = new File(path);
  151. if (!file.exists()) {
  152. return false;
  153. }
  154. int lastDot = file.getName().lastIndexOf(".");
  155. if (lastDot < 0) {
  156. return false;
  157. }
  158. String fileType = getFileType(file.getName(), lastDot);
  159. return TextUtils.equals("file_image", fileType);
  160. } catch (Exception e) {
  161. e.printStackTrace();
  162. }
  163. return false;
  164. }
  165. public static String getBase64Type(String str) {
  166. if (TextUtils.isEmpty(str)) {
  167. return "";
  168. }
  169. String type = "";
  170. switch (str) {
  171. case "data:application/msword;base64":
  172. type = "doc";
  173. case "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64":
  174. type = "docx";
  175. case "data:application/vnd.ms-excel;base64":
  176. type = "xls";
  177. case "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64":
  178. type = "xlsx";
  179. case "data:application/pdf;base64":
  180. type = "pdf";
  181. case "data:application/vnd.ms-powerpoint;base64":
  182. type = "ppt";
  183. case "data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64":
  184. type = "pptx";
  185. case "data:text/plain;base64":
  186. type = "txt";
  187. case "data:image/png;base64":
  188. type = "png";
  189. case "data:image/jpeg;base64":
  190. type = "jpg";
  191. }
  192. return type;
  193. }
  194. /**
  195. * 从sd卡取文件
  196. *
  197. * @param filename
  198. * @return
  199. */
  200. public String getFileFromSdcard(String filename) {
  201. ByteArrayOutputStream outputStream = null;
  202. FileInputStream fis = null;
  203. try {
  204. outputStream = new ByteArrayOutputStream();
  205. File file = new File(Environment.getExternalStorageDirectory(), filename);
  206. if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
  207. fis = new FileInputStream(file);
  208. int len = 0;
  209. byte[] data = new byte[1024];
  210. while ((len = fis.read(data)) != -1) {
  211. outputStream.write(data, 0, len);
  212. }
  213. }
  214. } catch (Exception e) {
  215. e.printStackTrace();
  216. } finally {
  217. try {
  218. outputStream.close();
  219. fis.close();
  220. } catch (IOException e) {
  221. }
  222. }
  223. return new String(outputStream.toByteArray());
  224. }
  225. /**
  226. * 保存文件到sd
  227. *
  228. * @param filename
  229. * @param content
  230. * @return
  231. */
  232. public static boolean saveContentToSdcard(String filename, String content) {
  233. boolean flag;
  234. FileOutputStream fos = null;
  235. content += "\r\n";
  236. try {
  237. File file = new File(filename);
  238. if (file.exists()) {
  239. file.mkdirs();
  240. }
  241. fos = new FileOutputStream(file, true);
  242. fos.write(content.getBytes());
  243. flag = true;
  244. } catch (Exception e) {
  245. e.printStackTrace();
  246. flag = false;
  247. } finally {
  248. try {
  249. if (fos != null) {
  250. fos.close();
  251. }
  252. } catch (IOException e) {
  253. }
  254. }
  255. return flag;
  256. }
  257. /**
  258. * 保存文件到sd
  259. *
  260. * @param
  261. * @param
  262. * @return
  263. */
  264. public static boolean saveFileToSdcard(String mPath, InputStream inputStream) {
  265. byte[] mData = null;
  266. try {
  267. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  268. int len = 0;
  269. byte[] bytes = new byte[1024];
  270. while ((len = inputStream.read(bytes)) != -1) {
  271. baos.write(bytes, 0, len);
  272. }
  273. mData = baos.toByteArray();
  274. } catch (IOException e) {
  275. e.printStackTrace();
  276. }
  277. try {
  278. FileOutputStream fos = new FileOutputStream(new File(mPath));
  279. fos.write(mData, 0, mData.length);
  280. return true;
  281. } catch (FileNotFoundException e) {
  282. e.printStackTrace();
  283. } catch (IOException e) {
  284. e.printStackTrace();
  285. }
  286. return false;
  287. }
  288. /**
  289. * 取得文件大小
  290. *
  291. * @param f
  292. * @return
  293. */
  294. public static long getFileSizes(File f) {
  295. long size = 0;
  296. try {
  297. if (f.exists()) {
  298. FileInputStream fis = null;
  299. fis = new FileInputStream(f);
  300. size = fis.available();
  301. } else {
  302. f.createNewFile();
  303. }
  304. } catch (Exception e) {
  305. }
  306. return size;
  307. }
  308. /**
  309. * 递归取得文件夹大小
  310. *
  311. * @param dir
  312. * @return
  313. * @throws Exception
  314. */
  315. public static long getFileSize(File dir) throws Exception {
  316. long size = 0;
  317. File flist[] = dir.listFiles();
  318. for (int i = 0; i < flist.length; i++) {
  319. if (flist[i].isDirectory()) {
  320. size = size + getFileSize(flist[i]);
  321. } else {
  322. size = size + flist[i].length();
  323. }
  324. }
  325. return size;
  326. }
  327. /**
  328. * 转换文件大小
  329. *
  330. * @param fileS
  331. * @return
  332. */
  333. public static String FormetFileSize(long fileS) {
  334. DecimalFormat df = new DecimalFormat("#.00");
  335. String fileSizeString = "";
  336. if (fileS < 1024) {
  337. fileSizeString = df.format((double) fileS) + "B";
  338. } else if (fileS < 1048576) {
  339. fileSizeString = df.format((double) fileS / 1024) + "K";
  340. } else if (fileS < 1073741824) {
  341. fileSizeString = df.format((double) fileS / 1048576) + "M";
  342. } else {
  343. fileSizeString = df.format((double) fileS / 1073741824) + "G";
  344. }
  345. return fileSizeString;
  346. }
  347. /**
  348. * 递归求取目录文件个数
  349. *
  350. * @param f
  351. * @return
  352. */
  353. public static long getlist(File f) {
  354. long size = 0;
  355. File flist[] = f.listFiles();
  356. size = flist.length;
  357. for (int i = 0; i < flist.length; i++) {
  358. if (flist[i].isDirectory()) {
  359. size = size + getlist(flist[i]);
  360. size--;
  361. }
  362. }
  363. return size;
  364. }
  365. /**
  366. * 在根目录下搜索文件
  367. *
  368. * @param keyword
  369. * @return
  370. */
  371. public static String searchFile(String keyword) {
  372. String result = "";
  373. File[] files = new File("/").listFiles();
  374. for (File file : files) {
  375. if (file.getName().indexOf(keyword) >= 0) {
  376. result += file.getPath() + "\n";
  377. }
  378. }
  379. if (result.equals("")) {
  380. result = "找不到文件!!";
  381. }
  382. return result;
  383. }
  384. /**
  385. *
  386. */
  387. public static List<String> search(File file, String[] ext) {
  388. List<String> list = new ArrayList<String>();
  389. if (file != null) {
  390. if (file.isDirectory()) {
  391. File[] listFile = file.listFiles();
  392. if (listFile != null) {
  393. for (int i = 0; i < listFile.length; i++) {
  394. search(listFile[i], ext);
  395. }
  396. }
  397. } else {
  398. String filename = file.getAbsolutePath();
  399. for (int i = 0; i < ext.length; i++) {
  400. if (filename.endsWith(ext[i])) {
  401. list.add(filename);
  402. break;
  403. }
  404. }
  405. }
  406. }
  407. return list;
  408. }
  409. /**
  410. * 查询文件
  411. *
  412. * @param file
  413. * @param keyword
  414. * @return
  415. */
  416. public static List<File> FindFile(File file, String keyword) {
  417. List<File> list = new ArrayList<File>();
  418. if (file.isDirectory()) {
  419. File[] files = file.listFiles();
  420. if (files != null) {
  421. for (File tempf : files) {
  422. if (tempf.isDirectory()) {
  423. if (tempf.getName().toLowerCase().lastIndexOf(keyword) > -1) {
  424. list.add(tempf);
  425. }
  426. list.addAll(FindFile(tempf, keyword));
  427. } else {
  428. if (tempf.getName().toLowerCase().lastIndexOf(keyword) > -1) {
  429. list.add(tempf);
  430. }
  431. }
  432. }
  433. }
  434. }
  435. return list;
  436. }
  437. /**
  438. * searchFile 查找文件并加入到ArrayList 当中去
  439. *
  440. * @param context
  441. * @param keyword
  442. * @param filepath
  443. * @return
  444. */
  445. public static List<Map<String, Object>> searchFile(Context context, String keyword, File filepath) {
  446. List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
  447. Map<String, Object> rowItem = null;
  448. int index = 0;
  449. // 判断SD卡是否存在
  450. if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  451. File[] files = filepath.listFiles();
  452. if (files.length > 0) {
  453. for (File file : files) {
  454. if (file.isDirectory()) {
  455. if (file.getName().toLowerCase().lastIndexOf(keyword) > -1) {
  456. rowItem = new HashMap<String, Object>();
  457. rowItem.put("number", index); // 加入序列号
  458. rowItem.put("fileName", file.getName());// 加入名称
  459. rowItem.put("path", file.getPath()); // 加入路径
  460. rowItem.put("size", file.length() + ""); // 加入文件大小
  461. list.add(rowItem);
  462. }
  463. // 如果目录可读就执行(一定要加,不然会挂掉)
  464. if (file.canRead()) {
  465. list.addAll(searchFile(context, keyword, file)); // 如果是目录,递归查找
  466. }
  467. } else {
  468. // 判断是文件,则进行文件名判断
  469. try {
  470. if (file.getName().indexOf(keyword) > -1 || file.getName().indexOf(keyword.toUpperCase()) > -1) {
  471. rowItem = new HashMap<String, Object>();
  472. rowItem.put("number", index); // 加入序列号
  473. rowItem.put("fileName", file.getName());// 加入名称
  474. rowItem.put("path", file.getPath()); // 加入路径
  475. rowItem.put("size", file.length() + ""); // 加入文件大小
  476. list.add(rowItem);
  477. index++;
  478. }
  479. } catch (Exception e) {
  480. }
  481. }
  482. }
  483. }
  484. }
  485. return list;
  486. }
  487. /**
  488. * 根据后缀得到文件类型
  489. *
  490. * @param fileName
  491. * @param pointIndex
  492. * @return
  493. */
  494. public static String getFileType(String fileName, int pointIndex) {
  495. String type = fileName.substring(pointIndex + 1).toLowerCase();
  496. if ("m4a".equalsIgnoreCase(type) || "xmf".equalsIgnoreCase(type) || "ogg".equalsIgnoreCase(type) || "wav".equalsIgnoreCase(type)
  497. || "m4a".equalsIgnoreCase(type) || "aiff".equalsIgnoreCase(type) || "midi".equalsIgnoreCase(type)
  498. || "vqf".equalsIgnoreCase(type) || "aac".equalsIgnoreCase(type) || "flac".equalsIgnoreCase(type)
  499. || "tak".equalsIgnoreCase(type) || "wv".equalsIgnoreCase(type)) {
  500. type = "file_audio";
  501. } else if ("mp3".equalsIgnoreCase(type) || "mid".equalsIgnoreCase(type)) {
  502. type = "file_mp3";
  503. } else if ("avi".equalsIgnoreCase(type) || "mp4".equalsIgnoreCase(type) || "dvd".equalsIgnoreCase(type)
  504. || "mid".equalsIgnoreCase(type) || "mov".equalsIgnoreCase(type) || "mkv".equalsIgnoreCase(type)
  505. || "mp2v".equalsIgnoreCase(type) || "mpe".equalsIgnoreCase(type) || "mpeg".equalsIgnoreCase(type)
  506. || "mpg".equalsIgnoreCase(type) || "asx".equalsIgnoreCase(type) || "asf".equalsIgnoreCase(type)
  507. || "flv".equalsIgnoreCase(type) || "navi".equalsIgnoreCase(type) || "divx".equalsIgnoreCase(type)
  508. || "rm".equalsIgnoreCase(type) || "rmvb".equalsIgnoreCase(type) || "dat".equalsIgnoreCase(type)
  509. || "mpa".equalsIgnoreCase(type) || "vob".equalsIgnoreCase(type) || "3gp".equalsIgnoreCase(type)
  510. || "swf".equalsIgnoreCase(type) || "wmv".equalsIgnoreCase(type)) {
  511. type = "file_video";
  512. } else if ("bmp".equalsIgnoreCase(type) || "pcx".equalsIgnoreCase(type) || "tiff".equalsIgnoreCase(type)
  513. || "gif".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type) || "tga".equalsIgnoreCase(type)
  514. || "exif".equalsIgnoreCase(type) || "fpx".equalsIgnoreCase(type) || "psd".equalsIgnoreCase(type)
  515. || "cdr".equalsIgnoreCase(type) || "raw".equalsIgnoreCase(type) || "eps".equalsIgnoreCase(type)
  516. || "gif".equalsIgnoreCase(type) || "jpg".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type)
  517. || "png".equalsIgnoreCase(type) || "hdri".equalsIgnoreCase(type) || "ai".equalsIgnoreCase(type)) {
  518. type = "file_image";
  519. } else if ("ppt".equalsIgnoreCase(type) || "doc".equalsIgnoreCase(type) || "xls".equalsIgnoreCase(type)
  520. || "pps".equalsIgnoreCase(type) || "xlsx".equalsIgnoreCase(type) || "xlsm".equalsIgnoreCase(type)
  521. || "pptx".equalsIgnoreCase(type) || "pptm".equalsIgnoreCase(type) || "ppsx".equalsIgnoreCase(type)
  522. || "maw".equalsIgnoreCase(type) || "mdb".equalsIgnoreCase(type) || "pot".equalsIgnoreCase(type)
  523. || "msg".equalsIgnoreCase(type) || "oft".equalsIgnoreCase(type) || "xlw".equalsIgnoreCase(type)
  524. || "wps".equalsIgnoreCase(type) || "rtf".equalsIgnoreCase(type) || "ppsm".equalsIgnoreCase(type)
  525. || "potx".equalsIgnoreCase(type) || "potm".equalsIgnoreCase(type) || "ppam".equalsIgnoreCase(type)) {
  526. type = "ic_file_office";
  527. } else if ("txt".equalsIgnoreCase(type) || "text".equalsIgnoreCase(type) || "chm".equalsIgnoreCase(type)
  528. || "hlp".equalsIgnoreCase(type) || "pdf".equalsIgnoreCase(type) || "doc".equalsIgnoreCase(type)
  529. || "docx".equalsIgnoreCase(type) || "docm".equalsIgnoreCase(type) || "dotx".equalsIgnoreCase(type)) {
  530. type = "file_text";
  531. } else if ("ini".equalsIgnoreCase(type) || "sys".equalsIgnoreCase(type) || "dll".equalsIgnoreCase(type)
  532. || "adt".equalsIgnoreCase(type)) {
  533. type = "file_system";
  534. } else if ("rar".equalsIgnoreCase(type) || "zip".equalsIgnoreCase(type) || "arj".equalsIgnoreCase(type)
  535. || "gz".equalsIgnoreCase(type) || "z".equalsIgnoreCase(type) || "7Z".equalsIgnoreCase(type) || "GZ".equalsIgnoreCase(type)
  536. || "BZ".equalsIgnoreCase(type) || "ZPAQ".equalsIgnoreCase(type)) {
  537. type = "ic_file_rar";
  538. } else if ("html".equalsIgnoreCase(type) || "htm".equalsIgnoreCase(type) || "java".equalsIgnoreCase(type)
  539. || "php".equalsIgnoreCase(type) || "asp".equalsIgnoreCase(type) || "aspx".equalsIgnoreCase(type)
  540. || "jsp".equalsIgnoreCase(type) || "shtml".equalsIgnoreCase(type) || "xml".equalsIgnoreCase(type)) {
  541. type = "file_web";
  542. } else if ("exe".equalsIgnoreCase(type) || "com".equalsIgnoreCase(type) || "bat".equalsIgnoreCase(type)
  543. || "iso".equalsIgnoreCase(type) || "msi".equalsIgnoreCase(type)) {
  544. type = "file_exe";
  545. } else if ("apk".equalsIgnoreCase(type)) {
  546. type = "ic_file_apk";
  547. } else {
  548. type = "ic_file_normal";
  549. }
  550. return type;
  551. }
  552. /**
  553. * 改变文件大小显示的内容
  554. *
  555. * @param size
  556. * @return
  557. */
  558. public static String changeFileSize(String size) {
  559. if (Integer.parseInt(size) > 1024) {
  560. size = Integer.parseInt(size) / 1024 + "K";
  561. } else if (Integer.parseInt(size) > (1024 * 1024)) {
  562. size = Integer.parseInt(size) / (1024 * 1024) + "M";
  563. } else if (Integer.parseInt(size) > (1024 * 1024 * 1024)) {
  564. size = Integer.parseInt(size) / (1024 * 1024 * 1024) + "G";
  565. } else {
  566. size += "B";
  567. }
  568. return size;
  569. }
  570. /**
  571. * 得到所有文件
  572. *
  573. * @param dir
  574. * @return
  575. */
  576. public static ArrayList<File> getAllFiles(File dir) {
  577. ArrayList<File> allFiles = new ArrayList<File>();
  578. // 递归取得目录下的所有文件及文件夹
  579. File[] files = dir.listFiles();
  580. for (int i = 0; i < files.length; i++) {
  581. File file = files[i];
  582. allFiles.add(file);
  583. if (file.isDirectory()) {
  584. getAllFiles(file);
  585. }
  586. }
  587. return allFiles;
  588. }
  589. /**
  590. * 判断文件MimeType 类型
  591. *
  592. * @param f
  593. * @return
  594. */
  595. public static String getMIMEType(File f) {
  596. String type = "";
  597. String fName = f.getName();
  598. /* 取得扩展名 */
  599. String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
  600. /* 依扩展名的类型决定MimeType */
  601. if (end.equalsIgnoreCase("m4a") || end.equalsIgnoreCase("mp3") || end.equalsIgnoreCase("mid") || end.equalsIgnoreCase("xmf")
  602. || end.equalsIgnoreCase("ogg") || end.equalsIgnoreCase("wav")) {
  603. type = "audio";
  604. } else if (end.equalsIgnoreCase("3gp") || end.equalsIgnoreCase("mp4")) {
  605. type = "video";
  606. } else if (end.equalsIgnoreCase("jpg") || end.equalsIgnoreCase("gif") || end.equalsIgnoreCase("png")
  607. || end.equalsIgnoreCase("jpeg") || end.equalsIgnoreCase("bmp")) {
  608. type = "image";
  609. } else if (end.equalsIgnoreCase("apk")) {
  610. /* android.permission.INSTALL_PACKAGES */
  611. type = "application/vnd.android.package-archive";
  612. } else if (end.equalsIgnoreCase("txt") || end.equalsIgnoreCase("java")) {
  613. /* android.permission.INSTALL_PACKAGES */
  614. type = "text";
  615. } else {
  616. type = "*";
  617. }
  618. /* 如果无法直接打开,就跳出软件列表给用户选择 */
  619. if (end.equalsIgnoreCase("apk")) {
  620. } else {
  621. type += "/*";
  622. }
  623. return type;
  624. }
  625. /**
  626. * 拷贝文件
  627. *
  628. * @param fromFile
  629. * @param toFile
  630. * @throws IOException
  631. */
  632. public static void copyFile(File fromFile, String toFile) throws IOException {
  633. FileInputStream from = null;
  634. FileOutputStream to = null;
  635. try {
  636. from = new FileInputStream(fromFile);
  637. to = new FileOutputStream(toFile);
  638. byte[] buffer = new byte[1024];
  639. int bytesRead;
  640. while ((bytesRead = from.read(buffer)) != -1)
  641. to.write(buffer, 0, bytesRead); // write
  642. } finally {
  643. if (from != null)
  644. try {
  645. from.close();
  646. } catch (IOException e) {
  647. Log.e(TAG, "", e);
  648. }
  649. if (to != null)
  650. try {
  651. to.close();
  652. } catch (IOException e) {
  653. Log.e(TAG, "", e);
  654. }
  655. }
  656. }
  657. /**
  658. * 创建文件
  659. *
  660. * @param file
  661. * @return
  662. */
  663. public static File createNewFile(File file) {
  664. try {
  665. if (file.exists()) {
  666. return file;
  667. }
  668. File dir = file.getParentFile();
  669. if (!dir.exists()) {
  670. dir.mkdirs();
  671. }
  672. if (!file.exists()) {
  673. file.createNewFile();
  674. }
  675. } catch (IOException e) {
  676. Log.e(TAG, "", e);
  677. return null;
  678. }
  679. return file;
  680. }
  681. /**
  682. * 创建文件
  683. *
  684. * @param path
  685. */
  686. public static File createNewFile(String path) {
  687. File file = new File(path);
  688. return createNewFile(file);
  689. }// end method createText()
  690. /**
  691. * 删除文件
  692. *
  693. * @param path
  694. */
  695. public static void deleteFile(String path) {
  696. if (TextUtils.isEmpty(path)) {
  697. return;
  698. }
  699. File file = new File(path);
  700. deleteFile(file);
  701. }
  702. /**
  703. * 删除文件
  704. *
  705. * @param file
  706. */
  707. public static void deleteFile(File file) {
  708. try {
  709. if (!file.exists()) {
  710. return;
  711. }
  712. if (file.isFile()) {
  713. file.delete();
  714. } else if (file.isDirectory()) {
  715. File files[] = file.listFiles();
  716. for (int i = 0; i < files.length; i++) {
  717. deleteFile(files[i]);
  718. }
  719. }
  720. file.delete();
  721. } catch (Exception e) {
  722. }
  723. }
  724. /**
  725. * 向Text文件中写入内容
  726. *
  727. * @param content
  728. * @return
  729. */
  730. public static boolean write(String path, String content) {
  731. return write(path, content, false);
  732. }
  733. public static boolean write(String path, String content, boolean append) {
  734. return write(new File(path), content, append);
  735. }
  736. public static boolean write(File file, String content) {
  737. return write(file, content, false);
  738. }
  739. /**
  740. * 写入文件
  741. *
  742. * @param file
  743. * @param content
  744. * @param append
  745. * @return
  746. */
  747. public static boolean write(File file, String content, boolean append) {
  748. if (file == null || TextUtils.isEmpty(content)) {
  749. return false;
  750. }
  751. if (!file.exists()) {
  752. file = createNewFile(file);
  753. }
  754. FileOutputStream fos = null;
  755. try {
  756. fos = new FileOutputStream(file, append);
  757. fos.write(content.getBytes());
  758. } catch (Exception e) {
  759. Log.e(TAG, "", e);
  760. return false;
  761. } finally {
  762. try {
  763. fos.close();
  764. } catch (IOException e) {
  765. Log.e(TAG, "", e);
  766. }
  767. fos = null;
  768. }
  769. return true;
  770. }
  771. /**
  772. * 获得文件名
  773. *
  774. * @param path
  775. * @return
  776. */
  777. public static String getFileName(String path) {
  778. if (TextUtils.isEmpty(path)) {
  779. return null;
  780. }
  781. File f = new File(path);
  782. String name = f.getName();
  783. f = null;
  784. return name;
  785. }
  786. /**
  787. * 读取文件内容,从第startLine行开始,读取lineCount行
  788. *
  789. * @param file
  790. * @param startLine
  791. * @param lineCount
  792. * @return 读到文字的list, 如果list.size<lineCount则说明读到文件末尾了
  793. */
  794. public static List<String> readFile(File file, int startLine, int lineCount) {
  795. if (file == null || startLine < 1 || lineCount < 1) {
  796. return null;
  797. }
  798. if (!file.exists()) {
  799. return null;
  800. }
  801. FileReader fileReader = null;
  802. List<String> list = null;
  803. try {
  804. list = new ArrayList<String>();
  805. fileReader = new FileReader(file);
  806. LineNumberReader lineReader = new LineNumberReader(fileReader);
  807. boolean end = false;
  808. for (int i = 1; i < startLine; i++) {
  809. if (lineReader.readLine() == null) {
  810. end = true;
  811. break;
  812. }
  813. }
  814. if (end == false) {
  815. for (int i = startLine; i < startLine + lineCount; i++) {
  816. String line = lineReader.readLine();
  817. if (line == null) {
  818. break;
  819. }
  820. list.add(line);
  821. }
  822. }
  823. } catch (Exception e) {
  824. Log.e(TAG, "read log error!", e);
  825. } finally {
  826. if (fileReader != null) {
  827. try {
  828. fileReader.close();
  829. } catch (IOException e) {
  830. e.printStackTrace();
  831. }
  832. }
  833. }
  834. return list;
  835. }
  836. /**
  837. * 创建文件夹
  838. *
  839. * @param dir
  840. * @return
  841. */
  842. public static boolean createDir(File dir) {
  843. try {
  844. if (!dir.exists()) {
  845. dir.mkdirs();
  846. }
  847. return true;
  848. } catch (Exception e) {
  849. Log.e(TAG, "create dir error", e);
  850. return false;
  851. }
  852. }
  853. /**
  854. * 在SD卡上创建目录
  855. *
  856. * @param dirName
  857. */
  858. public static File creatSDDir(String dirName) {
  859. File dir = new File(dirName);
  860. dir.mkdir();
  861. return dir;
  862. }
  863. /**
  864. * 判断SD卡上的文件是否存在
  865. */
  866. public static boolean isFileExist(String fileName) {
  867. File file = new File(fileName);
  868. return file == null ? false : file.exists();
  869. }
  870. /**
  871. * 将一个InputStream里面的数据写入到SD卡中
  872. */
  873. public static File write2SDFromInput(String path, String fileName, InputStream input) {
  874. File file = null;
  875. OutputStream output = null;
  876. try {
  877. creatSDDir(path);
  878. file = createNewFile(path + "/" + fileName);
  879. output = new FileOutputStream(file);
  880. byte buffer[] = new byte[1024];
  881. int len = -1;
  882. while ((len = input.read(buffer)) != -1) {
  883. output.write(buffer, 0, len);
  884. }
  885. output.flush();
  886. } catch (Exception e) {
  887. e.printStackTrace();
  888. } finally {
  889. try {
  890. output.close();
  891. } catch (Exception e) {
  892. e.printStackTrace();
  893. }
  894. }
  895. return file;
  896. }
  897. /**
  898. * 读取文件内容 从文件中一行一行的读取文件
  899. *
  900. * @param file
  901. * @return
  902. */
  903. public static String readFile(File file) {
  904. FileReader read = null;
  905. String content = "";
  906. String result = "";
  907. BufferedReader br = null;
  908. try {
  909. read = new FileReader(file);
  910. br = new BufferedReader(read);
  911. while ((content = br.readLine().toString().trim()) != null) {
  912. result += content + "\r\n";
  913. }
  914. } catch (Exception e) {
  915. e.printStackTrace();
  916. } finally {
  917. try {
  918. read.close();
  919. br.close();
  920. } catch (Exception e) {
  921. e.printStackTrace();
  922. }
  923. }
  924. return result;
  925. }
  926. /**
  927. * 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,
  928. * 特点是: File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变
  929. *
  930. * @param bmp
  931. * @param file
  932. */
  933. public static void compressBmpToFile(Bitmap bmp, File file) {
  934. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  935. int options = 100;// 个人喜欢从80开始,
  936. bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
  937. while (baos.toByteArray().length / 1024 > 100) {
  938. baos.reset();
  939. options -= 10;
  940. bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
  941. }
  942. try {
  943. FileOutputStream fos = new FileOutputStream(file);
  944. fos.write(baos.toByteArray());
  945. fos.flush();
  946. fos.close();
  947. } catch (Exception e) {
  948. e.printStackTrace();
  949. }
  950. }
  951. /**
  952. * 将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式
  953. * 特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩
  954. *
  955. * @param srcPath
  956. * @return
  957. */
  958. public static Bitmap compressImageFromFile(String srcPath, float pixWidth, float pixHeight) {
  959. BitmapFactory.Options options = new BitmapFactory.Options();
  960. options.inJustDecodeBounds = true;// 只读边,不读内容
  961. Bitmap bitmap = BitmapFactory.decodeFile(srcPath, options);
  962. options.inJustDecodeBounds = false;
  963. int w = options.outWidth;
  964. int h = options.outHeight;
  965. //float pixWidth = 800f;//
  966. //float pixHeight = 480f;//
  967. int scale = 1;
  968. if (w > h && w > pixWidth) {
  969. scale = (int) (options.outWidth / pixWidth);
  970. } else if (w < h && h > pixHeight) {
  971. scale = (int) (options.outHeight / pixHeight);
  972. }
  973. if (scale <= 0)
  974. scale = 1;
  975. options.inSampleSize = scale;// 设置采样率
  976. options.inPreferredConfig = Bitmap.Config.ARGB_8888;// 该模式是默认的,可不设
  977. options.inPurgeable = true;// 同时设置才会有效
  978. options.inInputShareable = true;// 。当系统内存不够时候图片自动被回收
  979. bitmap = BitmapFactory.decodeFile(srcPath, options);
  980. // return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
  981. // 其实是无效的,大家尽管尝试
  982. return bitmap;
  983. }
  984. /**
  985. * 指定分辨率和清晰度的图片压缩
  986. */
  987. public void transImage(String fromFile, String toFile, int width, int height, int quality) {
  988. try {
  989. Bitmap bitmap = BitmapFactory.decodeFile(fromFile);
  990. int bitmapWidth = bitmap.getWidth();
  991. int bitmapHeight = bitmap.getHeight();
  992. // 缩放图片的尺寸
  993. float scaleWidth = (float) width / bitmapWidth;
  994. float scaleHeight = (float) height / bitmapHeight;
  995. Matrix matrix = new Matrix();
  996. matrix.postScale(scaleWidth, scaleHeight);
  997. // 产生缩放后的Bitmap对象
  998. Bitmap resizeBitmap = (Bitmap) Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
  999. // save file
  1000. File myCaptureFile = new File(toFile);
  1001. FileOutputStream out = new FileOutputStream(myCaptureFile);
  1002. if (resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)) {
  1003. out.flush();
  1004. out.close();
  1005. }
  1006. if (!bitmap.isRecycled()) {
  1007. bitmap.recycle();//记得释放资源,否则会内存溢出
  1008. }
  1009. if (!resizeBitmap.isRecycled()) {
  1010. resizeBitmap.recycle();
  1011. }
  1012. } catch (FileNotFoundException e) {
  1013. e.printStackTrace();
  1014. } catch (IOException ex) {
  1015. ex.printStackTrace();
  1016. }
  1017. }
  1018. public static String getFilePath(Bitmap bitmap) {
  1019. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  1020. bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);
  1021. String path = Environment.getExternalStorageDirectory() + "/dayaWhiteBroad";
  1022. File dir = new File(path);
  1023. if (!dir.exists()) {
  1024. dir.mkdirs();
  1025. }
  1026. File file = new File(path + "/" + System.currentTimeMillis() + ".png");
  1027. try {
  1028. file.createNewFile();
  1029. FileOutputStream fos = new FileOutputStream(file);
  1030. InputStream is = new ByteArrayInputStream(baos.toByteArray());
  1031. int x = 0;
  1032. byte[] b = new byte[1024 * 100];
  1033. while ((x = is.read(b)) != -1) {
  1034. fos.write(b, 0, x);
  1035. }
  1036. fos.close();
  1037. } catch (Exception e) {
  1038. e.printStackTrace();
  1039. }
  1040. return file.getPath();
  1041. }
  1042. /**
  1043. * 保存图片到图库
  1044. *
  1045. * @param bmp
  1046. */
  1047. public static void saveImageToGallery(Bitmap bmp, String path) {
  1048. // 首先保存图片
  1049. File file = new File(path);
  1050. try {
  1051. FileOutputStream fos = new FileOutputStream(file);
  1052. bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
  1053. fos.flush();
  1054. fos.close();
  1055. } catch (FileNotFoundException e) {
  1056. e.printStackTrace();
  1057. } catch (IOException e) {
  1058. e.printStackTrace();
  1059. }
  1060. }
  1061. public static boolean writeFileToSDCard(ResponseBody body, String filePath, String fileName) {
  1062. if (null == body) {
  1063. return false;
  1064. }
  1065. try {
  1066. File parentFile = new File(filePath);
  1067. if (!parentFile.exists()) {
  1068. parentFile.mkdirs();
  1069. }
  1070. File futureStudioIconFile = new File(parentFile, fileName);
  1071. InputStream inputStream = null;
  1072. OutputStream outputStream = null;
  1073. try {
  1074. byte[] fileReader = new byte[4096];
  1075. long fileSize = body.contentLength();
  1076. long fileSizeDownloaded = 0;
  1077. inputStream = body.byteStream();
  1078. outputStream = new FileOutputStream(futureStudioIconFile);
  1079. while (true) {
  1080. int read = inputStream.read(fileReader);
  1081. if (read == -1) {
  1082. break;
  1083. }
  1084. outputStream.write(fileReader, 0, read);
  1085. fileSizeDownloaded += read;
  1086. }
  1087. outputStream.flush();
  1088. return true;
  1089. } catch (IOException e) {
  1090. return false;
  1091. } finally {
  1092. if (inputStream != null) {
  1093. inputStream.close();
  1094. }
  1095. if (outputStream != null) {
  1096. outputStream.close();
  1097. }
  1098. }
  1099. } catch (IOException e) {
  1100. return false;
  1101. }
  1102. }
  1103. public static String uriToFile(Context context, Uri uri, String filePath) {
  1104. File privateFile = new File(filePath);
  1105. File fileParent = privateFile.getParentFile();
  1106. if (!fileParent.exists()) {
  1107. fileParent.mkdirs();
  1108. }
  1109. if (privateFile.exists()) return privateFile.getAbsolutePath();
  1110. InputStream ist = null;
  1111. OutputStream ost = null;
  1112. try {
  1113. privateFile.createNewFile();
  1114. ist = context.getContentResolver().openInputStream(uri);
  1115. ost = new FileOutputStream(privateFile);
  1116. byte[] buffer = new byte[4096];
  1117. int byteCount = 0;
  1118. while ((byteCount = ist.read(buffer)) != -1) { // 循环从输入流读取 buffer字节
  1119. ost.write(buffer, 0, byteCount); // 将读取的输入流写入到输出流
  1120. }
  1121. } catch (IOException e) {
  1122. return "";
  1123. } finally {
  1124. try {
  1125. if (ist != null) {
  1126. ist.close();
  1127. }
  1128. if (ost != null) {
  1129. ost.close();
  1130. }
  1131. } catch (IOException e) {
  1132. return "";
  1133. }
  1134. }
  1135. return privateFile.getAbsolutePath();
  1136. }
  1137. public static Intent startIntent(Context context, String path) {
  1138. if (TextUtils.isEmpty(path)) {
  1139. return null;
  1140. }
  1141. Intent intent = null;
  1142. switch (path.substring(path.lastIndexOf(".") + 1)) {
  1143. case "pdf":
  1144. intent = getPdfFileIntent(context, path);
  1145. break;
  1146. case "text":
  1147. intent = getTextFileIntent(context, path);
  1148. break;
  1149. case "html":
  1150. intent = getHtmlFileIntent(path);
  1151. break;
  1152. case "doc":
  1153. case "docx":
  1154. intent = getWordFileIntent(context, path);
  1155. break;
  1156. case "xls":
  1157. case "xlsx":
  1158. intent = getHtmlFileIntent(path);
  1159. break;
  1160. }
  1161. return intent;
  1162. }
  1163. //android获取一个用于打开HTML文件的intent
  1164. public static Intent getHtmlFileIntent(String Path) {
  1165. File file = new File(Path);
  1166. Uri uri = Uri.parse(file.toString()).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(file.toString()).build();
  1167. Intent intent = new Intent("android.intent.action.VIEW");
  1168. intent.setDataAndType(uri, "text/html");
  1169. return intent;
  1170. }
  1171. //android获取一个用于打开图片文件的intent
  1172. public static Intent getImageFileIntent(String Path) {
  1173. File file = new File(Path);
  1174. Intent intent = new Intent("android.intent.action.VIEW");
  1175. intent.addCategory("android.intent.category.DEFAULT");
  1176. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1177. Uri uri = Uri.fromFile(file);
  1178. intent.setDataAndType(uri, "image/*");
  1179. return intent;
  1180. }
  1181. //android获取一个用于打开PDF文件的intent
  1182. public static Intent getPdfFileIntent(Context context, String Path) {
  1183. File file = new File(Path);
  1184. Intent intent = new Intent("android.intent.action.VIEW");
  1185. intent.addCategory("android.intent.category.DEFAULT");
  1186. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1187. Uri uri = null;
  1188. final boolean isN = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
  1189. if (isN) {
  1190. uri = FileProvider.getUriForFile(context, context.getPackageName() + ".FileProvider", file);
  1191. } else {
  1192. uri = Uri.fromFile(file);
  1193. }
  1194. intent.setDataAndType(uri, "application/pdf");
  1195. return intent;
  1196. }
  1197. //android获取一个用于打开文本文件的intent
  1198. public static Intent getTextFileIntent(Context context, String Path) {
  1199. File file = new File(Path);
  1200. Intent intent = new Intent("android.intent.action.VIEW");
  1201. intent.addCategory("android.intent.category.DEFAULT");
  1202. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1203. Uri uri = null;
  1204. final boolean isN = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
  1205. if (isN) {
  1206. uri = FileProvider.getUriForFile(context, context.getPackageName() + ".FileProvider", file);
  1207. } else {
  1208. uri = Uri.fromFile(file);
  1209. }
  1210. intent.setDataAndType(uri, "text/plain");
  1211. return intent;
  1212. }
  1213. //android获取一个用于打开音频文件的intent
  1214. public static Intent getAudioFileIntent(String Path) {
  1215. File file = new File(Path);
  1216. Intent intent = new Intent("android.intent.action.VIEW");
  1217. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1218. intent.putExtra("oneshot", 0);
  1219. intent.putExtra("configchange", 0);
  1220. Uri uri = Uri.fromFile(file);
  1221. intent.setDataAndType(uri, "audio/*");
  1222. return intent;
  1223. }
  1224. //android获取一个用于打开视频文件的intent
  1225. public static Intent getVideoFileIntent(String Path) {
  1226. File file = new File(Path);
  1227. Intent intent = new Intent("android.intent.action.VIEW");
  1228. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1229. intent.putExtra("oneshot", 0);
  1230. intent.putExtra("configchange", 0);
  1231. Uri uri = Uri.fromFile(file);
  1232. intent.setDataAndType(uri, "video/*");
  1233. return intent;
  1234. }
  1235. //android获取一个用于打开CHM文件的intent
  1236. public static Intent getChmFileIntent(String Path) {
  1237. File file = new File(Path);
  1238. Intent intent = new Intent("android.intent.action.VIEW");
  1239. intent.addCategory("android.intent.category.DEFAULT");
  1240. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1241. Uri uri = Uri.fromFile(file);
  1242. intent.setDataAndType(uri, "application/x-chm");
  1243. return intent;
  1244. }
  1245. //android获取一个用于打开Word文件的intent
  1246. public static Intent getWordFileIntent(Context context, String Path) {
  1247. File file = new File(Path);
  1248. Intent intent = new Intent("android.intent.action.VIEW");
  1249. intent.addCategory("android.intent.category.DEFAULT");
  1250. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1251. Uri uri = null;
  1252. final boolean isN = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
  1253. if (isN) {
  1254. uri = FileProvider.getUriForFile(context, context.getPackageName() + ".FileProvider", file);
  1255. } else {
  1256. uri = Uri.fromFile(file);
  1257. }
  1258. intent.setDataAndType(uri, "application/msword");
  1259. return intent;
  1260. }
  1261. //android获取一个用于打开Excel文件的intent
  1262. public static Intent getExcelFileIntent(String Path) {
  1263. File file = new File(Path);
  1264. Intent intent = new Intent("android.intent.action.VIEW");
  1265. intent.addCategory("android.intent.category.DEFAULT");
  1266. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1267. Uri uri = Uri.fromFile(file);
  1268. intent.setDataAndType(uri, "application/vnd.ms-excel");
  1269. return intent;
  1270. }
  1271. //android获取一个用于打开PPT文件的intent
  1272. public static Intent getPPTFileIntent(String Path) {
  1273. File file = new File(Path);
  1274. Intent intent = new Intent("android.intent.action.VIEW");
  1275. intent.addCategory("android.intent.category.DEFAULT");
  1276. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1277. Uri uri = Uri.fromFile(file);
  1278. intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
  1279. return intent;
  1280. }
  1281. //android获取一个用于打开apk文件的intent
  1282. public static Intent getApkFileIntent(String Path) {
  1283. File file = new File(Path);
  1284. Intent intent = new Intent();
  1285. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1286. intent.setAction(Intent.ACTION_VIEW);
  1287. intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
  1288. return intent;
  1289. }
  1290. public static final String DOCUMENTS_DIR = "documents";
  1291. @SuppressLint("NewApi")
  1292. public static String getPath(final Context context, final Uri uri) {
  1293. final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
  1294. // DocumentProvider
  1295. if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
  1296. // ExternalStorageProvider
  1297. if (isExternalStorageDocument(uri)) {
  1298. final String docId = DocumentsContract.getDocumentId(uri);
  1299. final String[] split = docId.split(":");
  1300. final String type = split[0];
  1301. if ("primary".equalsIgnoreCase(type)) {
  1302. return Environment.getExternalStorageDirectory() + "/" + split[1];
  1303. }
  1304. }
  1305. // DownloadsProvider
  1306. else if (isDownloadsDocument(uri)) {
  1307. final String id = DocumentsContract.getDocumentId(uri);
  1308. if (id != null && id.startsWith("raw:")) {
  1309. return id.substring(4);
  1310. }
  1311. String[] contentUriPrefixesToTry = new String[]{
  1312. "content://downloads/public_downloads",
  1313. "content://downloads/my_downloads"
  1314. };
  1315. for (String contentUriPrefix : contentUriPrefixesToTry) {
  1316. Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
  1317. try {
  1318. String path = getDataColumn(context, contentUri, null, null);
  1319. if (path != null && !path.equals("")) {
  1320. return path;
  1321. }
  1322. } catch (Exception e) {
  1323. }
  1324. }
  1325. // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
  1326. String fileName = getFileName(context, uri);
  1327. File cacheDir = getDocumentCacheDir(context);
  1328. File file = generateFileName(fileName, cacheDir);
  1329. String destinationPath = null;
  1330. if (file != null) {
  1331. destinationPath = file.getAbsolutePath();
  1332. saveFileFromUri(context, uri, destinationPath);
  1333. }
  1334. return destinationPath;
  1335. }
  1336. // MediaProvider
  1337. else if (isMediaDocument(uri)) {
  1338. final String docId = DocumentsContract.getDocumentId(uri);
  1339. final String[] split = docId.split(":");
  1340. final String type = split[0];
  1341. Uri contentUri = null;
  1342. if ("image".equals(type)) {
  1343. contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  1344. } else if ("video".equals(type)) {
  1345. contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
  1346. } else if ("audio".equals(type)) {
  1347. contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  1348. }
  1349. final String selection = "_id=?";
  1350. final String[] selectionArgs = new String[]{split[1]};
  1351. return getDataColumn(context, contentUri, selection, selectionArgs);
  1352. }
  1353. }
  1354. // MediaStore (and general)
  1355. else if ("content".equalsIgnoreCase(uri.getScheme())) {
  1356. String path = getDataColumn(context, uri, null, null);
  1357. if (path != null && !path.equals("")) return path;
  1358. // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
  1359. String fileName = getFileName(context, uri);
  1360. File cacheDir = getDocumentCacheDir(context);
  1361. File file = generateFileName(fileName, cacheDir);
  1362. String destinationPath = null;
  1363. if (file != null) {
  1364. destinationPath = file.getAbsolutePath();
  1365. saveFileFromUri(context, uri, destinationPath);
  1366. }
  1367. return destinationPath;
  1368. }
  1369. // File
  1370. else if ("file".equalsIgnoreCase(uri.getScheme())) {
  1371. return uri.getPath();
  1372. }
  1373. return null;
  1374. }
  1375. /**
  1376. * @param uri The Uri to check.
  1377. * @return Whether the Uri authority is ExternalStorageProvider.
  1378. */
  1379. public static boolean isExternalStorageDocument(Uri uri) {
  1380. return "com.android.externalstorage.documents".equals(uri.getAuthority());
  1381. }
  1382. /**
  1383. * @param uri The Uri to check.
  1384. * @return Whether the Uri authority is DownloadsProvider.
  1385. */
  1386. public static boolean isDownloadsDocument(Uri uri) {
  1387. return "com.android.providers.downloads.documents".equals(uri.getAuthority());
  1388. }
  1389. /**
  1390. * @param uri The Uri to check.
  1391. * @return Whether the Uri authority is MediaProvider.
  1392. */
  1393. public static boolean isMediaDocument(Uri uri) {
  1394. return "com.android.providers.media.documents".equals(uri.getAuthority());
  1395. }
  1396. public static String getDataColumn(Context context, Uri uri, String selection,
  1397. String[] selectionArgs) {
  1398. Cursor cursor = null;
  1399. final String column = "_data";
  1400. final String[] projection = {column};
  1401. String path = "";
  1402. try {
  1403. cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
  1404. null);
  1405. if (cursor != null && cursor.moveToFirst()) {
  1406. final int column_index = cursor.getColumnIndexOrThrow(column);
  1407. path = cursor.getString(column_index);
  1408. return path;
  1409. }
  1410. } catch (Exception e) {
  1411. e.printStackTrace();
  1412. } finally {
  1413. if (cursor != null)
  1414. cursor.close();
  1415. }
  1416. return path;
  1417. }
  1418. public static String getFileName(@NonNull Context context, Uri uri) {
  1419. String mimeType = context.getContentResolver().getType(uri);
  1420. String filename = null;
  1421. if (mimeType == null && context != null) {
  1422. String path = getPath(context, uri);
  1423. if (path == null) {
  1424. filename = getName(uri.toString());
  1425. } else {
  1426. File file = new File(path);
  1427. filename = file.getName();
  1428. }
  1429. } else {
  1430. Cursor returnCursor = context.getContentResolver().query(uri, null,
  1431. null, null, null);
  1432. if (returnCursor != null) {
  1433. int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
  1434. returnCursor.moveToFirst();
  1435. filename = returnCursor.getString(nameIndex);
  1436. returnCursor.close();
  1437. }
  1438. }
  1439. return filename;
  1440. }
  1441. public static String getName(String filename) {
  1442. if (filename == null) {
  1443. return null;
  1444. }
  1445. int index = filename.lastIndexOf('/');
  1446. return filename.substring(index + 1);
  1447. }
  1448. public static File getDocumentCacheDir(@NonNull Context context) {
  1449. File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
  1450. if (!dir.exists()) {
  1451. dir.mkdirs();
  1452. }
  1453. return dir;
  1454. }
  1455. @Nullable
  1456. public static File generateFileName(@Nullable String name, File directory) {
  1457. if (name == null) {
  1458. return null;
  1459. }
  1460. File file = new File(directory, name);
  1461. if (file.exists()) {
  1462. String fileName = name;
  1463. String extension = "";
  1464. int dotIndex = name.lastIndexOf('.');
  1465. if (dotIndex > 0) {
  1466. fileName = name.substring(0, dotIndex);
  1467. extension = name.substring(dotIndex);
  1468. }
  1469. int index = 0;
  1470. while (file.exists()) {
  1471. index++;
  1472. name = fileName + '(' + index + ')' + extension;
  1473. file = new File(directory, name);
  1474. }
  1475. }
  1476. try {
  1477. if (!file.createNewFile()) {
  1478. return null;
  1479. }
  1480. } catch (IOException e) {
  1481. return null;
  1482. }
  1483. return file;
  1484. }
  1485. private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
  1486. InputStream is = null;
  1487. BufferedOutputStream bos = null;
  1488. try {
  1489. is = context.getContentResolver().openInputStream(uri);
  1490. bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
  1491. byte[] buf = new byte[1024];
  1492. is.read(buf);
  1493. do {
  1494. bos.write(buf);
  1495. } while (is.read(buf) != -1);
  1496. } catch (IOException e) {
  1497. e.printStackTrace();
  1498. } finally {
  1499. try {
  1500. if (is != null) is.close();
  1501. if (bos != null) bos.close();
  1502. } catch (IOException e) {
  1503. e.printStackTrace();
  1504. }
  1505. }
  1506. }
  1507. //bitmap转为base64
  1508. public static String bitmapToBase64(Bitmap bitmap) {
  1509. String result = null;
  1510. ByteArrayOutputStream baos = null;
  1511. try {
  1512. if (bitmap != null) {
  1513. baos = new ByteArrayOutputStream();
  1514. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
  1515. baos.flush();
  1516. baos.close();
  1517. byte[] bitmapBytes = baos.toByteArray();
  1518. result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
  1519. }
  1520. } catch (IOException e) {
  1521. e.printStackTrace();
  1522. } finally {
  1523. try {
  1524. if (baos != null) {
  1525. baos.flush();
  1526. baos.close();
  1527. }
  1528. } catch (IOException e) {
  1529. e.printStackTrace();
  1530. }
  1531. }
  1532. return result;
  1533. }
  1534. //base64转为bitmap
  1535. public static Bitmap base64ToBitmap(String base64Data) {
  1536. byte[] bytes = Base64.decode(base64Data, Base64.NO_WRAP);
  1537. return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  1538. }
  1539. }