12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075 |
- package com.cooleshow.base.utils;
- import android.app.Application;
- import android.content.ContentResolver;
- import android.content.ContentValues;
- import android.content.Context;
- import android.content.Intent;
- import android.content.res.AssetFileDescriptor;
- import android.database.Cursor;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.media.MediaScannerConnection;
- import android.net.Uri;
- import android.os.Build;
- import android.os.Environment;
- import android.os.StatFs;
- import android.provider.MediaStore;
- import android.provider.OpenableColumns;
- import android.text.TextUtils;
- import android.util.Base64;
- import android.util.Log;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileFilter;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.URL;
- import java.nio.file.Files;
- import java.security.DigestInputStream;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Date;
- import java.util.List;
- import java.util.Locale;
- import javax.net.ssl.HttpsURLConnection;
- import okhttp3.ResponseBody;
- /**
- * <pre>
- * author: Blankj
- * blog : http://blankj.com
- * time : 2016/05/03
- * desc : utils about file
- * </pre>
- */
- public final class FileUtils {
- public static final String filesDirectory = "coolexiu";
- public static final String examDownloadDirectory = "examDownload";
- private static final String LINE_SEP = System.getProperty("line.separator");
- public static String getCacheDir(Context context) {
- String cacheDir = context.getExternalCacheDir().getAbsolutePath();
- return cacheDir;
- }
- private FileUtils() {
- throw new UnsupportedOperationException("u can't instantiate me...");
- }
- /**
- * Return the file by path.
- *
- * @param filePath The path of file.
- * @return the file
- */
- public static File getFileByPath(final String filePath) {
- return UtilsBridge.isSpace(filePath) ? null : new File(filePath);
- }
- /**
- * Return whether the file exists.
- *
- * @param file The file.
- * @return {@code true}: yes<br>{@code false}: no
- */
- public static boolean isFileExists(final File file) {
- if (file == null) return false;
- if (file.exists()) {
- return true;
- }
- return isFileExists(file.getAbsolutePath());
- }
- /**
- * Return whether the file exists.
- *
- * @param filePath The path of file.
- * @return {@code true}: yes<br>{@code false}: no
- */
- public static boolean isFileExists(final String filePath) {
- File file = getFileByPath(filePath);
- if (file == null) return false;
- if (file.exists()) {
- return true;
- }
- return isFileExistsApi29(filePath);
- }
- private static boolean isFileExistsApi29(String filePath) {
- if (Build.VERSION.SDK_INT >= 29) {
- try {
- Uri uri = Uri.parse(filePath);
- ContentResolver cr = Utils.getApp().getContentResolver();
- AssetFileDescriptor afd = cr.openAssetFileDescriptor(uri, "r");
- if (afd == null) return false;
- try {
- afd.close();
- } catch (IOException ignore) {
- }
- } catch (FileNotFoundException e) {
- return false;
- }
- return true;
- }
- return false;
- }
- /**
- * Rename the file.
- *
- * @param filePath The path of file.
- * @param newName The new name of file.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean rename(final String filePath, final String newName) {
- return rename(getFileByPath(filePath), newName);
- }
- /**
- * Rename the file.
- *
- * @param file The file.
- * @param newName The new name of file.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean rename(final File file, final String newName) {
- // file is null then return false
- if (file == null) return false;
- // file doesn't exist then return false
- if (!file.exists()) return false;
- // the new name is space then return false
- if (UtilsBridge.isSpace(newName)) return false;
- // the new name equals old name then return true
- if (newName.equals(file.getName())) return true;
- File newFile = new File(file.getParent() + File.separator + newName);
- // the new name of file exists then return false
- return !newFile.exists()
- && file.renameTo(newFile);
- }
- /**
- * Return whether it is a directory.
- *
- * @param dirPath The path of directory.
- * @return {@code true}: yes<br>{@code false}: no
- */
- public static boolean isDir(final String dirPath) {
- return isDir(getFileByPath(dirPath));
- }
- /**
- * Return whether it is a directory.
- *
- * @param file The file.
- * @return {@code true}: yes<br>{@code false}: no
- */
- public static boolean isDir(final File file) {
- return file != null && file.exists() && file.isDirectory();
- }
- /**
- * Return whether it is a file.
- *
- * @param filePath The path of file.
- * @return {@code true}: yes<br>{@code false}: no
- */
- public static boolean isFile(final String filePath) {
- return isFile(getFileByPath(filePath));
- }
- /**
- * Return whether it is a file.
- *
- * @param file The file.
- * @return {@code true}: yes<br>{@code false}: no
- */
- public static boolean isFile(final File file) {
- return file != null && file.exists() && file.isFile();
- }
- /**
- * Create a directory if it doesn't exist, otherwise do nothing.
- *
- * @param dirPath The path of directory.
- * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise
- */
- public static boolean createOrExistsDir(final String dirPath) {
- return createOrExistsDir(getFileByPath(dirPath));
- }
- /**
- * Create a directory if it doesn't exist, otherwise do nothing.
- *
- * @param file The file.
- * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise
- */
- public static boolean createOrExistsDir(final File file) {
- return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
- }
- /**
- * Create a file if it doesn't exist, otherwise do nothing.
- *
- * @param filePath The path of file.
- * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise
- */
- public static boolean createOrExistsFile(final String filePath) {
- return createOrExistsFile(getFileByPath(filePath));
- }
- /**
- * Create a file if it doesn't exist, otherwise do nothing.
- *
- * @param file The file.
- * @return {@code true}: exists or creates successfully<br>{@code false}: otherwise
- */
- public static boolean createOrExistsFile(final File file) {
- if (file == null) return false;
- if (file.exists()) return file.isFile();
- if (!createOrExistsDir(file.getParentFile())) return false;
- try {
- return file.createNewFile();
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- }
- /**
- * Create a file if it doesn't exist, otherwise delete old file before creating.
- *
- * @param filePath The path of file.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean createFileByDeleteOldFile(final String filePath) {
- return createFileByDeleteOldFile(getFileByPath(filePath));
- }
- /**
- * Create a file if it doesn't exist, otherwise delete old file before creating.
- *
- * @param file The file.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean createFileByDeleteOldFile(final File file) {
- if (file == null) return false;
- // file exists and unsuccessfully delete then return false
- if (file.exists() && !file.delete()) return false;
- if (!createOrExistsDir(file.getParentFile())) return false;
- try {
- return file.createNewFile();
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- }
- /**
- * Copy the directory or file.
- *
- * @param srcPath The path of source.
- * @param destPath The path of destination.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean copy(final String srcPath,
- final String destPath) {
- return copy(getFileByPath(srcPath), getFileByPath(destPath), null);
- }
- /**
- * Copy the directory or file.
- *
- * @param srcPath The path of source.
- * @param destPath The path of destination.
- * @param listener The replace listener.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean copy(final String srcPath,
- final String destPath,
- final OnReplaceListener listener) {
- return copy(getFileByPath(srcPath), getFileByPath(destPath), listener);
- }
- /**
- * Copy the directory or file.
- *
- * @param src The source.
- * @param dest The destination.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean copy(final File src,
- final File dest) {
- return copy(src, dest, null);
- }
- /**
- * Copy the directory or file.
- *
- * @param src The source.
- * @param dest The destination.
- * @param listener The replace listener.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean copy(final File src,
- final File dest,
- final OnReplaceListener listener) {
- if (src == null) return false;
- if (src.isDirectory()) {
- return copyDir(src, dest, listener);
- }
- return copyFile(src, dest, listener);
- }
- /**
- * Copy the directory.
- *
- * @param srcDir The source directory.
- * @param destDir The destination directory.
- * @param listener The replace listener.
- * @return {@code true}: success<br>{@code false}: fail
- */
- private static boolean copyDir(final File srcDir,
- final File destDir,
- final OnReplaceListener listener) {
- return copyOrMoveDir(srcDir, destDir, listener, false);
- }
- /**
- * Copy the file.
- *
- * @param srcFile The source file.
- * @param destFile The destination file.
- * @param listener The replace listener.
- * @return {@code true}: success<br>{@code false}: fail
- */
- private static boolean copyFile(final File srcFile,
- final File destFile,
- final OnReplaceListener listener) {
- return copyOrMoveFile(srcFile, destFile, listener, false);
- }
- /**
- * Move the directory or file.
- *
- * @param srcPath The path of source.
- * @param destPath The path of destination.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean move(final String srcPath,
- final String destPath) {
- return move(getFileByPath(srcPath), getFileByPath(destPath), null);
- }
- /**
- * Move the directory or file.
- *
- * @param srcPath The path of source.
- * @param destPath The path of destination.
- * @param listener The replace listener.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean move(final String srcPath,
- final String destPath,
- final OnReplaceListener listener) {
- return move(getFileByPath(srcPath), getFileByPath(destPath), listener);
- }
- /**
- * Move the directory or file.
- *
- * @param src The source.
- * @param dest The destination.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean move(final File src,
- final File dest) {
- return move(src, dest, null);
- }
- /**
- * Move the directory or file.
- *
- * @param src The source.
- * @param dest The destination.
- * @param listener The replace listener.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean move(final File src,
- final File dest,
- final OnReplaceListener listener) {
- if (src == null) return false;
- if (src.isDirectory()) {
- return moveDir(src, dest, listener);
- }
- return moveFile(src, dest, listener);
- }
- /**
- * Move the directory.
- *
- * @param srcDir The source directory.
- * @param destDir The destination directory.
- * @param listener The replace listener.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean moveDir(final File srcDir,
- final File destDir,
- final OnReplaceListener listener) {
- return copyOrMoveDir(srcDir, destDir, listener, true);
- }
- /**
- * Move the file.
- *
- * @param srcFile The source file.
- * @param destFile The destination file.
- * @param listener The replace listener.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean moveFile(final File srcFile,
- final File destFile,
- final OnReplaceListener listener) {
- return copyOrMoveFile(srcFile, destFile, listener, true);
- }
- private static boolean copyOrMoveDir(final File srcDir,
- final File destDir,
- final OnReplaceListener listener,
- final boolean isMove) {
- if (srcDir == null || destDir == null) return false;
- // destDir's path locate in srcDir's path then return false
- String srcPath = srcDir.getPath() + File.separator;
- String destPath = destDir.getPath() + File.separator;
- if (destPath.contains(srcPath)) return false;
- if (!srcDir.exists() || !srcDir.isDirectory()) return false;
- if (!createOrExistsDir(destDir)) return false;
- File[] files = srcDir.listFiles();
- if (files != null && files.length > 0) {
- for (File file : files) {
- File oneDestFile = new File(destPath + file.getName());
- if (file.isFile()) {
- if (!copyOrMoveFile(file, oneDestFile, listener, isMove)) return false;
- } else if (file.isDirectory()) {
- if (!copyOrMoveDir(file, oneDestFile, listener, isMove)) return false;
- }
- }
- }
- return !isMove || deleteDir(srcDir);
- }
- private static boolean copyOrMoveFile(final File srcFile,
- final File destFile,
- final OnReplaceListener listener,
- final boolean isMove) {
- if (srcFile == null || destFile == null) return false;
- // srcFile equals destFile then return false
- if (srcFile.equals(destFile)) return false;
- // srcFile doesn't exist or isn't a file then return false
- if (!srcFile.exists() || !srcFile.isFile()) return false;
- if (destFile.exists()) {
- if (listener == null || listener.onReplace(srcFile, destFile)) {// require delete the old file
- if (!destFile.delete()) {// unsuccessfully delete then return false
- return false;
- }
- } else {
- return true;
- }
- }
- if (!createOrExistsDir(destFile.getParentFile())) return false;
- try {
- return UtilsBridge.writeFileFromIS(destFile.getAbsolutePath(), new FileInputStream(srcFile))
- && !(isMove && !deleteFile(srcFile));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- return false;
- }
- }
- /**
- * Delete the directory.
- *
- * @param filePath The path of file.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean delete(final String filePath) {
- return delete(getFileByPath(filePath));
- }
- /**
- * Delete the directory.
- *
- * @param file The file.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean delete(final File file) {
- if (file == null) return false;
- if (file.isDirectory()) {
- return deleteDir(file);
- }
- return deleteFile(file);
- }
- /**
- * Delete the directory.
- *
- * @param dir The directory.
- * @return {@code true}: success<br>{@code false}: fail
- */
- private static boolean deleteDir(final File dir) {
- if (dir == null) return false;
- // dir doesn't exist then return true
- if (!dir.exists()) return true;
- // dir isn't a directory then return false
- if (!dir.isDirectory()) return false;
- File[] files = dir.listFiles();
- if (files != null && files.length > 0) {
- for (File file : files) {
- if (file.isFile()) {
- if (!file.delete()) return false;
- } else if (file.isDirectory()) {
- if (!deleteDir(file)) return false;
- }
- }
- }
- return dir.delete();
- }
- /**
- * Delete the file.
- *
- * @param file The file.
- * @return {@code true}: success<br>{@code false}: fail
- */
- private static boolean deleteFile(final File file) {
- return file != null && (!file.exists() || file.isFile() && file.delete());
- }
- /**
- * 删除文件
- *
- * @param file
- */
- public static void deleteFile1(File file) {
- try {
- if (!file.exists()) {
- return;
- }
- if (file.isFile()) {
- file.delete();
- } else if (file.isDirectory()) {
- File files[] = file.listFiles();
- for (int i = 0; i < files.length; i++) {
- deleteFile(files[i]);
- }
- }
- file.delete();
- } catch (Exception e) {
- }
- }
- /**
- * Delete the all in directory.
- *
- * @param dirPath The path of directory.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean deleteAllInDir(final String dirPath) {
- return deleteAllInDir(getFileByPath(dirPath));
- }
- /**
- * Delete the all in directory.
- *
- * @param dir The directory.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean deleteAllInDir(final File dir) {
- return deleteFilesInDirWithFilter(dir, new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return true;
- }
- });
- }
- /**
- * Delete all files in directory.
- *
- * @param dirPath The path of directory.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean deleteFilesInDir(final String dirPath) {
- return deleteFilesInDir(getFileByPath(dirPath));
- }
- /**
- * Delete all files in directory.
- *
- * @param dir The directory.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean deleteFilesInDir(final File dir) {
- return deleteFilesInDirWithFilter(dir, new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return pathname.isFile();
- }
- });
- }
- /**
- * Delete all files that satisfy the filter in directory.
- *
- * @param dirPath The path of directory.
- * @param filter The filter.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean deleteFilesInDirWithFilter(final String dirPath,
- final FileFilter filter) {
- return deleteFilesInDirWithFilter(getFileByPath(dirPath), filter);
- }
- /**
- * Delete all files that satisfy the filter in directory.
- *
- * @param dir The directory.
- * @param filter The filter.
- * @return {@code true}: success<br>{@code false}: fail
- */
- public static boolean deleteFilesInDirWithFilter(final File dir, final FileFilter filter) {
- if (dir == null || filter == null) return false;
- // dir doesn't exist then return true
- if (!dir.exists()) return true;
- // dir isn't a directory then return false
- if (!dir.isDirectory()) return false;
- File[] files = dir.listFiles();
- if (files != null && files.length != 0) {
- for (File file : files) {
- if (filter.accept(file)) {
- if (file.isFile()) {
- if (!file.delete()) return false;
- } else if (file.isDirectory()) {
- if (!deleteDir(file)) return false;
- }
- }
- }
- }
- return true;
- }
- /**
- * Return the files in directory.
- * <p>Doesn't traverse subdirectories</p>
- *
- * @param dirPath The path of directory.
- * @return the files in directory
- */
- public static List<File> listFilesInDir(final String dirPath) {
- return listFilesInDir(dirPath, null);
- }
- /**
- * Return the files in directory.
- * <p>Doesn't traverse subdirectories</p>
- *
- * @param dir The directory.
- * @return the files in directory
- */
- public static List<File> listFilesInDir(final File dir) {
- return listFilesInDir(dir, null);
- }
- /**
- * Return the files in directory.
- * <p>Doesn't traverse subdirectories</p>
- *
- * @param dirPath The path of directory.
- * @param comparator The comparator to determine the order of the list.
- * @return the files in directory
- */
- public static List<File> listFilesInDir(final String dirPath, Comparator<File> comparator) {
- return listFilesInDir(getFileByPath(dirPath), false, comparator);
- }
- /**
- * Return the files in directory.
- * <p>Doesn't traverse subdirectories</p>
- *
- * @param dir The directory.
- * @param comparator The comparator to determine the order of the list.
- * @return the files in directory
- */
- public static List<File> listFilesInDir(final File dir, Comparator<File> comparator) {
- return listFilesInDir(dir, false, comparator);
- }
- /**
- * Return the files in directory.
- *
- * @param dirPath The path of directory.
- * @param isRecursive True to traverse subdirectories, false otherwise.
- * @return the files in directory
- */
- public static List<File> listFilesInDir(final String dirPath, final boolean isRecursive) {
- return listFilesInDir(getFileByPath(dirPath), isRecursive);
- }
- /**
- * Return the files in directory.
- *
- * @param dir The directory.
- * @param isRecursive True to traverse subdirectories, false otherwise.
- * @return the files in directory
- */
- public static List<File> listFilesInDir(final File dir, final boolean isRecursive) {
- return listFilesInDir(dir, isRecursive, null);
- }
- /**
- * Return the files in directory.
- *
- * @param dirPath The path of directory.
- * @param isRecursive True to traverse subdirectories, false otherwise.
- * @param comparator The comparator to determine the order of the list.
- * @return the files in directory
- */
- public static List<File> listFilesInDir(final String dirPath,
- final boolean isRecursive,
- final Comparator<File> comparator) {
- return listFilesInDir(getFileByPath(dirPath), isRecursive, comparator);
- }
- /**
- * Return the files in directory.
- *
- * @param dir The directory.
- * @param isRecursive True to traverse subdirectories, false otherwise.
- * @param comparator The comparator to determine the order of the list.
- * @return the files in directory
- */
- public static List<File> listFilesInDir(final File dir,
- final boolean isRecursive,
- final Comparator<File> comparator) {
- return listFilesInDirWithFilter(dir, new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return true;
- }
- }, isRecursive, comparator);
- }
- /**
- * Return the files that satisfy the filter in directory.
- * <p>Doesn't traverse subdirectories</p>
- *
- * @param dirPath The path of directory.
- * @param filter The filter.
- * @return the files that satisfy the filter in directory
- */
- public static List<File> listFilesInDirWithFilter(final String dirPath,
- final FileFilter filter) {
- return listFilesInDirWithFilter(getFileByPath(dirPath), filter);
- }
- /**
- * Return the files that satisfy the filter in directory.
- * <p>Doesn't traverse subdirectories</p>
- *
- * @param dir The directory.
- * @param filter The filter.
- * @return the files that satisfy the filter in directory
- */
- public static List<File> listFilesInDirWithFilter(final File dir,
- final FileFilter filter) {
- return listFilesInDirWithFilter(dir, filter, false, null);
- }
- /**
- * Return the files that satisfy the filter in directory.
- * <p>Doesn't traverse subdirectories</p>
- *
- * @param dirPath The path of directory.
- * @param filter The filter.
- * @param comparator The comparator to determine the order of the list.
- * @return the files that satisfy the filter in directory
- */
- public static List<File> listFilesInDirWithFilter(final String dirPath,
- final FileFilter filter,
- final Comparator<File> comparator) {
- return listFilesInDirWithFilter(getFileByPath(dirPath), filter, comparator);
- }
- /**
- * Return the files that satisfy the filter in directory.
- * <p>Doesn't traverse subdirectories</p>
- *
- * @param dir The directory.
- * @param filter The filter.
- * @param comparator The comparator to determine the order of the list.
- * @return the files that satisfy the filter in directory
- */
- public static List<File> listFilesInDirWithFilter(final File dir,
- final FileFilter filter,
- final Comparator<File> comparator) {
- return listFilesInDirWithFilter(dir, filter, false, comparator);
- }
- /**
- * Return the files that satisfy the filter in directory.
- *
- * @param dirPath The path of directory.
- * @param filter The filter.
- * @param isRecursive True to traverse subdirectories, false otherwise.
- * @return the files that satisfy the filter in directory
- */
- public static List<File> listFilesInDirWithFilter(final String dirPath,
- final FileFilter filter,
- final boolean isRecursive) {
- return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive);
- }
- /**
- * Return the files that satisfy the filter in directory.
- *
- * @param dir The directory.
- * @param filter The filter.
- * @param isRecursive True to traverse subdirectories, false otherwise.
- * @return the files that satisfy the filter in directory
- */
- public static List<File> listFilesInDirWithFilter(final File dir,
- final FileFilter filter,
- final boolean isRecursive) {
- return listFilesInDirWithFilter(dir, filter, isRecursive, null);
- }
- /**
- * Return the files that satisfy the filter in directory.
- *
- * @param dirPath The path of directory.
- * @param filter The filter.
- * @param isRecursive True to traverse subdirectories, false otherwise.
- * @param comparator The comparator to determine the order of the list.
- * @return the files that satisfy the filter in directory
- */
- public static List<File> listFilesInDirWithFilter(final String dirPath,
- final FileFilter filter,
- final boolean isRecursive,
- final Comparator<File> comparator) {
- return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive, comparator);
- }
- /**
- * Return the files that satisfy the filter in directory.
- *
- * @param dir The directory.
- * @param filter The filter.
- * @param isRecursive True to traverse subdirectories, false otherwise.
- * @param comparator The comparator to determine the order of the list.
- * @return the files that satisfy the filter in directory
- */
- public static List<File> listFilesInDirWithFilter(final File dir,
- final FileFilter filter,
- final boolean isRecursive,
- final Comparator<File> comparator) {
- List<File> files = listFilesInDirWithFilterInner(dir, filter, isRecursive);
- if (comparator != null) {
- Collections.sort(files, comparator);
- }
- return files;
- }
- private static List<File> listFilesInDirWithFilterInner(final File dir,
- final FileFilter filter,
- final boolean isRecursive) {
- List<File> list = new ArrayList<>();
- if (!isDir(dir)) return list;
- File[] files = dir.listFiles();
- if (files != null && files.length > 0) {
- for (File file : files) {
- if (filter.accept(file)) {
- list.add(file);
- }
- if (isRecursive && file.isDirectory()) {
- list.addAll(listFilesInDirWithFilterInner(file, filter, true));
- }
- }
- }
- return list;
- }
- /**
- * Return the time that the file was last modified.
- *
- * @param filePath The path of file.
- * @return the time that the file was last modified
- */
- public static long getFileLastModified(final String filePath) {
- return getFileLastModified(getFileByPath(filePath));
- }
- /**
- * Return the time that the file was last modified.
- *
- * @param file The file.
- * @return the time that the file was last modified
- */
- public static long getFileLastModified(final File file) {
- if (file == null) return -1;
- return file.lastModified();
- }
- /**
- * Return the charset of file simply.
- *
- * @param filePath The path of file.
- * @return the charset of file simply
- */
- public static String getFileCharsetSimple(final String filePath) {
- return getFileCharsetSimple(getFileByPath(filePath));
- }
- /**
- * Return the charset of file simply.
- *
- * @param file The file.
- * @return the charset of file simply
- */
- public static String getFileCharsetSimple(final File file) {
- if (file == null) return "";
- if (isUtf8(file)) return "UTF-8";
- int p = 0;
- InputStream is = null;
- try {
- is = new BufferedInputStream(new FileInputStream(file));
- p = (is.read() << 8) + is.read();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (is != null) {
- is.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- switch (p) {
- case 0xfffe:
- return "Unicode";
- case 0xfeff:
- return "UTF-16BE";
- default:
- return "GBK";
- }
- }
- /**
- * Return whether the charset of file is utf8.
- *
- * @param filePath The path of file.
- * @return {@code true}: yes<br>{@code false}: no
- */
- public static boolean isUtf8(final String filePath) {
- return isUtf8(getFileByPath(filePath));
- }
- /**
- * Return whether the charset of file is utf8.
- *
- * @param file The file.
- * @return {@code true}: yes<br>{@code false}: no
- */
- public static boolean isUtf8(final File file) {
- if (file == null) return false;
- InputStream is = null;
- try {
- byte[] bytes = new byte[24];
- is = new BufferedInputStream(new FileInputStream(file));
- int read = is.read(bytes);
- if (read != -1) {
- byte[] readArr = new byte[read];
- System.arraycopy(bytes, 0, readArr, 0, read);
- return isUtf8(readArr) == 100;
- } else {
- return false;
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (is != null) {
- is.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return false;
- }
- /**
- * UTF-8编码方式
- * ----------------------------------------------
- * 0xxxxxxx
- * 110xxxxx 10xxxxxx
- * 1110xxxx 10xxxxxx 10xxxxxx
- * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
- */
- private static int isUtf8(byte[] raw) {
- int i, len;
- int utf8 = 0, ascii = 0;
- if (raw.length > 3) {
- if ((raw[0] == (byte) 0xEF) && (raw[1] == (byte) 0xBB) && (raw[2] == (byte) 0xBF)) {
- return 100;
- }
- }
- len = raw.length;
- int child = 0;
- for (i = 0; i < len; ) {
- // UTF-8 byte shouldn't be FF and FE
- if ((raw[i] & (byte) 0xFF) == (byte) 0xFF || (raw[i] & (byte) 0xFE) == (byte) 0xFE) {
- return 0;
- }
- if (child == 0) {
- // ASCII format is 0x0*******
- if ((raw[i] & (byte) 0x7F) == raw[i] && raw[i] != 0) {
- ascii++;
- } else if ((raw[i] & (byte) 0xC0) == (byte) 0xC0) {
- // 0x11****** maybe is UTF-8
- for (int bit = 0; bit < 8; bit++) {
- if ((((byte) (0x80 >> bit)) & raw[i]) == ((byte) (0x80 >> bit))) {
- child = bit;
- } else {
- break;
- }
- }
- utf8++;
- }
- i++;
- } else {
- child = (raw.length - i > child) ? child : (raw.length - i);
- boolean currentNotUtf8 = false;
- for (int children = 0; children < child; children++) {
- // format must is 0x10******
- if ((raw[i + children] & ((byte) 0x80)) != ((byte) 0x80)) {
- if ((raw[i + children] & (byte) 0x7F) == raw[i + children] && raw[i] != 0) {
- // ASCII format is 0x0*******
- ascii++;
- }
- currentNotUtf8 = true;
- }
- }
- if (currentNotUtf8) {
- utf8--;
- i++;
- } else {
- utf8 += child;
- i += child;
- }
- child = 0;
- }
- }
- // UTF-8 contains ASCII
- if (ascii == len) {
- return 100;
- }
- return (int) (100 * ((float) (utf8 + ascii) / (float) len));
- }
- /**
- * Return the number of lines of file.
- *
- * @param filePath The path of file.
- * @return the number of lines of file
- */
- public static int getFileLines(final String filePath) {
- return getFileLines(getFileByPath(filePath));
- }
- /**
- * Return the number of lines of file.
- *
- * @param file The file.
- * @return the number of lines of file
- */
- public static int getFileLines(final File file) {
- int count = 1;
- InputStream is = null;
- try {
- is = new BufferedInputStream(new FileInputStream(file));
- byte[] buffer = new byte[1024];
- int readChars;
- if (LINE_SEP.endsWith("\n")) {
- while ((readChars = is.read(buffer, 0, 1024)) != -1) {
- for (int i = 0; i < readChars; ++i) {
- if (buffer[i] == '\n') ++count;
- }
- }
- } else {
- while ((readChars = is.read(buffer, 0, 1024)) != -1) {
- for (int i = 0; i < readChars; ++i) {
- if (buffer[i] == '\r') ++count;
- }
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (is != null) {
- is.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return count;
- }
- /**
- * Return the size.
- *
- * @param filePath The path of file.
- * @return the size
- */
- public static String getSize(final String filePath) {
- return getSize(getFileByPath(filePath));
- }
- /**
- * Return the size.
- *
- * @param file The directory.
- * @return the size
- */
- public static String getSize(final File file) {
- if (file == null) return "";
- if (file.isDirectory()) {
- return getDirSize(file);
- }
- return getFileSize(file);
- }
- /**
- * Return the size of directory.
- *
- * @param dir The directory.
- * @return the size of directory
- */
- private static String getDirSize(final File dir) {
- long len = getDirLength(dir);
- return len == -1 ? "" : UtilsBridge.byte2FitMemorySize(len);
- }
- /**
- * Return the size of file.
- *
- * @param file The file.
- * @return the length of file
- */
- private static String getFileSize(final File file) {
- long len = getFileLength(file);
- return len == -1 ? "" : UtilsBridge.byte2FitMemorySize(len);
- }
- /**
- * Return the length.
- *
- * @param filePath The path of file.
- * @return the length
- */
- public static long getLength(final String filePath) {
- return getLength(getFileByPath(filePath));
- }
- /**
- * Return the length.
- *
- * @param file The file.
- * @return the length
- */
- public static long getLength(final File file) {
- if (file == null) return 0;
- if (file.isDirectory()) {
- return getDirLength(file);
- }
- return getFileLength(file);
- }
- /**
- * Return the length of directory.
- *
- * @param dir The directory.
- * @return the length of directory
- */
- private static long getDirLength(final File dir) {
- if (!isDir(dir)) return 0;
- long len = 0;
- File[] files = dir.listFiles();
- if (files != null && files.length > 0) {
- for (File file : files) {
- if (file.isDirectory()) {
- len += getDirLength(file);
- } else {
- len += file.length();
- }
- }
- }
- return len;
- }
- /**
- * Return the length of file.
- *
- * @param filePath The path of file.
- * @return the length of file
- */
- public static long getFileLength(final String filePath) {
- boolean isURL = filePath.matches("[a-zA-z]+://[^\\s]*");
- if (isURL) {
- try {
- HttpsURLConnection conn = (HttpsURLConnection) new URL(filePath).openConnection();
- conn.setRequestProperty("Accept-Encoding", "identity");
- conn.connect();
- if (conn.getResponseCode() == 200) {
- return conn.getContentLength();
- }
- return -1;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return getFileLength(getFileByPath(filePath));
- }
- /**
- * Return the length of file.
- *
- * @param file The file.
- * @return the length of file
- */
- private static long getFileLength(final File file) {
- if (!isFile(file)) return -1;
- return file.length();
- }
- /**
- * Return the MD5 of file.
- *
- * @param filePath The path of file.
- * @return the md5 of file
- */
- public static String getFileMD5ToString(final String filePath) {
- File file = UtilsBridge.isSpace(filePath) ? null : new File(filePath);
- return getFileMD5ToString(file);
- }
- /**
- * Return the MD5 of file.
- *
- * @param file The file.
- * @return the md5 of file
- */
- public static String getFileMD5ToString(final File file) {
- return UtilsBridge.bytes2HexString(getFileMD5(file));
- }
- /**
- * Return the MD5 of file.
- *
- * @param filePath The path of file.
- * @return the md5 of file
- */
- public static byte[] getFileMD5(final String filePath) {
- return getFileMD5(getFileByPath(filePath));
- }
- /**
- * Return the MD5 of file.
- *
- * @param file The file.
- * @return the md5 of file
- */
- public static byte[] getFileMD5(final File file) {
- if (file == null) return null;
- DigestInputStream dis = null;
- try {
- FileInputStream fis = new FileInputStream(file);
- MessageDigest md = MessageDigest.getInstance("MD5");
- dis = new DigestInputStream(fis, md);
- byte[] buffer = new byte[1024 * 256];
- while (true) {
- if (!(dis.read(buffer) > 0)) break;
- }
- md = dis.getMessageDigest();
- return md.digest();
- } catch (NoSuchAlgorithmException | IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (dis != null) {
- dis.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- /**
- * Return the file's path of directory.
- *
- * @param file The file.
- * @return the file's path of directory
- */
- public static String getDirName(final File file) {
- if (file == null) return "";
- return getDirName(file.getAbsolutePath());
- }
- /**
- * Return the file's path of directory.
- *
- * @param filePath The path of file.
- * @return the file's path of directory
- */
- public static String getDirName(final String filePath) {
- if (UtilsBridge.isSpace(filePath)) return "";
- int lastSep = filePath.lastIndexOf(File.separator);
- return lastSep == -1 ? "" : filePath.substring(0, lastSep + 1);
- }
- /**
- * Return the name of file.
- *
- * @param file The file.
- * @return the name of file
- */
- public static String getFileName(final File file) {
- if (file == null) return "";
- return getFileName(file.getAbsolutePath());
- }
- /**
- * Return the name of file.
- *
- * @param filePath The path of file.
- * @return the name of file
- */
- public static String getFileName(final String filePath) {
- if (UtilsBridge.isSpace(filePath)) return "";
- int lastSep = filePath.lastIndexOf(File.separator);
- return lastSep == -1 ? filePath : filePath.substring(lastSep + 1);
- }
- /**
- * Return the name of file without extension.
- *
- * @param file The file.
- * @return the name of file without extension
- */
- public static String getFileNameNoExtension(final File file) {
- if (file == null) return "";
- return getFileNameNoExtension(file.getPath());
- }
- /**
- * Return the name of file without extension.
- *
- * @param filePath The path of file.
- * @return the name of file without extension
- */
- public static String getFileNameNoExtension(final String filePath) {
- if (UtilsBridge.isSpace(filePath)) return "";
- int lastPoi = filePath.lastIndexOf('.');
- int lastSep = filePath.lastIndexOf(File.separator);
- if (lastSep == -1) {
- return (lastPoi == -1 ? filePath : filePath.substring(0, lastPoi));
- }
- if (lastPoi == -1 || lastSep > lastPoi) {
- return filePath.substring(lastSep + 1);
- }
- return filePath.substring(lastSep + 1, lastPoi);
- }
- /**
- * Return the extension of file.
- *
- * @param file The file.
- * @return the extension of file
- */
- public static String getFileExtension(final File file) {
- if (file == null) return "";
- return getFileExtension(file.getPath());
- }
- /**
- * Return the extension of file.
- *
- * @param filePath The path of file.
- * @return the extension of file
- */
- public static String getFileExtension(final String filePath) {
- if (UtilsBridge.isSpace(filePath)) return "";
- int lastPoi = filePath.lastIndexOf('.');
- int lastSep = filePath.lastIndexOf(File.separator);
- if (lastPoi == -1 || lastSep >= lastPoi) return "";
- return filePath.substring(lastPoi + 1);
- }
- /**
- * Notify system to scan the file.
- *
- * @param filePath The path of file.
- */
- public static void notifySystemToScan(final String filePath) {
- notifySystemToScan(getFileByPath(filePath));
- }
- /**
- * Notify system to scan the file.
- *
- * @param file The file.
- */
- public static void notifySystemToScan(final File file) {
- if (file == null || !file.exists()) return;
- Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
- intent.setData(Uri.parse("file://" + file.getAbsolutePath()));
- Utils.getApp().sendBroadcast(intent);
- }
- /**
- * Return the total size of file system.
- *
- * @param anyPathInFs Any path in file system.
- * @return the total size of file system
- */
- public static long getFsTotalSize(String anyPathInFs) {
- if (TextUtils.isEmpty(anyPathInFs)) return 0;
- StatFs statFs = new StatFs(anyPathInFs);
- long blockSize;
- long totalSize;
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
- blockSize = statFs.getBlockSizeLong();
- totalSize = statFs.getBlockCountLong();
- } else {
- blockSize = statFs.getBlockSize();
- totalSize = statFs.getBlockCount();
- }
- return blockSize * totalSize;
- }
- /**
- * Return the available size of file system.
- *
- * @param anyPathInFs Any path in file system.
- * @return the available size of file system
- */
- public static long getFsAvailableSize(final String anyPathInFs) {
- if (TextUtils.isEmpty(anyPathInFs)) return 0;
- StatFs statFs = new StatFs(anyPathInFs);
- long blockSize;
- long availableSize;
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
- blockSize = statFs.getBlockSizeLong();
- availableSize = statFs.getAvailableBlocksLong();
- } else {
- blockSize = statFs.getBlockSize();
- availableSize = statFs.getAvailableBlocks();
- }
- return blockSize * availableSize;
- }
- ///////////////////////////////////////////////////////////////////////////
- // interface
- ///////////////////////////////////////////////////////////////////////////
- public interface OnReplaceListener {
- boolean onReplace(File srcFile, File destFile);
- }
- public static boolean writeFileToSDCard(ResponseBody body, String filePath, String fileName) {
- if (null == body) {
- return false;
- }
- try {
- File futureStudioIconFile = new File(filePath + File.separator + fileName);
- InputStream inputStream = null;
- OutputStream outputStream = null;
- try {
- byte[] fileReader = new byte[4096];
- long fileSize = body.contentLength();
- long fileSizeDownloaded = 0;
- inputStream = body.byteStream();
- outputStream = new FileOutputStream(futureStudioIconFile);
- while (true) {
- int read = inputStream.read(fileReader);
- if (read == -1) {
- break;
- }
- outputStream.write(fileReader, 0, read);
- fileSizeDownloaded += read;
- }
- outputStream.flush();
- return true;
- } catch (IOException e) {
- return false;
- } finally {
- if (inputStream != null) {
- inputStream.close();
- }
- if (outputStream != null) {
- outputStream.close();
- }
- }
- } catch (IOException e) {
- return false;
- }
- }
- public static String getFilePath(Bitmap bitmap) {
- LogUtils.i("pq", "getFilePath bitmap:" + bitmap);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);
- String path = FileUtils.getCacheDir(Utils.getApp(), FileUtils.filesDirectory) + "/WhiteBroad";
- LogUtils.i("pq", "path:" + path);
- File dir = new File(path);
- if (!dir.exists()) {
- dir.mkdirs();
- }
- File file = new File(dir, System.currentTimeMillis() + ".png");
- // File file = new File(path + "/" + System.currentTimeMillis() + ".png");
- try {
- createOrExistsFile(file);
- FileOutputStream fos = new FileOutputStream(file);
- InputStream is = new ByteArrayInputStream(baos.toByteArray());
- int x = 0;
- byte[] b = new byte[1024 * 100];
- while ((x = is.read(b)) != -1) {
- fos.write(b, 0, x);
- }
- fos.close();
- } catch (Exception e) {
- LogUtils.i("pq", "Exception:" + e.getMessage());
- e.printStackTrace();
- }
- LogUtils.i("pq", "file path:" + file.getPath());
- return file.getPath();
- }
- public static String getCacheDir(Context context, String directory) {
- String fileDir;
- try {
- File file = new File(context.getExternalCacheDir() + File.separator + directory);
- if (!file.exists()) {
- file.mkdirs();
- }
- fileDir = file.getAbsolutePath();
- return fileDir;
- } catch (Exception e) {
- return "";
- }
- }
- public static String getCacheDir2(Context context, String directory) {
- String fileDir;
- try {
- File file = new File(context.getCacheDir() + File.separator + directory);
- if (!file.exists()) {
- file.mkdirs();
- }
- fileDir = file.getAbsolutePath();
- return fileDir;
- } catch (Exception e) {
- return "";
- }
- }
- /**
- * 判断SD卡上的文件是否存在
- */
- public static boolean isFileExist(String fileName) {
- File file = new File(fileName);
- return file == null ? false : file.exists();
- }
- /**
- * 获取本地文件
- *
- * @param uri
- * @param context
- * @return
- */
- public static String getFilePathForN(Uri uri, Context context) {
- Uri returnUri = uri;
- Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
- int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
- int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
- returnCursor.moveToFirst();
- String name = (returnCursor.getString(nameIndex));
- String size = (Long.toString(returnCursor.getLong(sizeIndex)));
- File file = new File(context.getFilesDir(), name);
- try {
- InputStream inputStream = context.getContentResolver().openInputStream(uri);
- FileOutputStream outputStream = new FileOutputStream(file);
- int read = 0;
- int maxBufferSize = 1 * 1024 * 1024;
- int bytesAvailable = inputStream.available();
- //int bufferSize = 1024;
- int bufferSize = Math.min(bytesAvailable, maxBufferSize);
- final byte[] buffers = new byte[bufferSize];
- while ((read = inputStream.read(buffers)) != -1) {
- outputStream.write(buffers, 0, read);
- }
- Log.e("File Size", "Size " + file.length());
- inputStream.close();
- outputStream.close();
- Log.e("File Path", "Path " + file.getPath());
- Log.e("File Size", "Size " + file.length());
- } catch (Exception e) {
- Log.e("Exception", e.getMessage());
- }
- return file.getPath();
- }
- public static File saveBase64ImgToLocalFile(String base64) throws Exception {
- byte[] bytes;
- if (base64.startsWith("data:image/png;base64")) {
- String[] split = base64.split(",");
- bytes = Base64.decode(split[1], Base64.DEFAULT);
- } else {
- bytes = Base64.decode(base64, Base64.DEFAULT);
- }
- Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
- File parentFile = new File(FileUtils.getCacheDir(Utils.getApp()) + File.separator + "img");
- if (!parentFile.exists()) {
- parentFile.mkdirs();
- }
- String targetFileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()) + ".png";
- File file = new File(parentFile, targetFileName);
- FileUtils.saveImag(bitmap, file.getAbsolutePath());
- if (file != null && file.exists()) {
- try {
- MediaStore.Images.Media.insertImage(Utils.getApp().getContentResolver(),
- file.getAbsolutePath(), file.getName(), null);
- // 最后通知图库更新
- Utils.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
- Uri.fromFile(new File(file.getPath()))));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- return new File(file.getAbsolutePath());
- }
- /**
- * 保存图片
- *
- * @param bmp
- */
- public static void saveImag(Bitmap bmp, String path) throws Exception {
- // 首先保存图片
- File file = new File(path);
- FileOutputStream fos = new FileOutputStream(file);
- bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
- fos.flush();
- fos.close();
- }
- /**
- * 将assets中的sf2文件保存到sd卡供midi使用
- *
- * @param application
- */
- public static void CopyMidiFile(Application application) {
- try {
- File f = new File(getCacheDir(application,"colexiu") + "/dysf.sf2");
- if (f.exists()) {
- if (f.length() < 1024 * 1024 * 38) {
- //如果文件存在,并且低于38M
- //目前没有md5校验,所以先这样处理文件完整性的问题
- f.delete();
- }
- }
- if (!f.exists()) {
- InputStream is = application.getAssets().open("soundfont.sf2");
- if (is == null) {
- return;
- }
- f.createNewFile();
- OutputStream os = new FileOutputStream(f);
- byte[] data = new byte[1024];
- int len = 0;
- while ((len = is.read(data)) != -1) {
- os.write(data, 0, len);
- }
- is.close();
- os.close();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * 保存图片到图库
- *
- * @param bmp
- */
- public static void saveImageToLocal(Bitmap bmp, String path) {
- // 首先保存图片
- File file = new File(path);
- try {
- FileOutputStream fos = new FileOutputStream(file);
- bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
- fos.flush();
- fos.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static File saveImgToLocalFile(Bitmap bitmap) {
- File parentFile = new File(FileUtils.getCacheDir(Utils.getApp()) + File.separator + "share");
- if (!parentFile.exists()) {
- parentFile.mkdirs();
- }
- String targetFileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()) + ".png";
- File file = new File(parentFile, targetFileName);
- saveImageToLocalForJPEG(bitmap, file.getAbsolutePath());
- return new File(file.getAbsolutePath());
- }
- /**
- * 保存图片到图库
- *
- * @param bmp
- */
- public static void saveImageToLocalForJPEG(Bitmap bmp, String path) {
- // 首先保存图片
- File file = new File(path);
- try {
- FileOutputStream fos = new FileOutputStream(file);
- bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
- fos.flush();
- fos.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static String getCompressPath() {
- String compressPath = getCacheDir(Utils.getApp()) + File.separator + "compress";
- File file = new File(compressPath);
- if (!file.exists()) {
- file.mkdirs();
- }
- return compressPath;
- }
- public static boolean isMatchTargetFileType(String targetType, String filePath) {
- try {
- Log.i("FileUtils", "filePath:" + filePath);
- if (TextUtils.isEmpty(targetType)) {
- Log.i("FileUtils", "targetType is null");
- return true;
- }
- if (TextUtils.equals(targetType, "video") || TextUtils.equals(targetType, "img")) {
- //忽略video或者img格式
- Log.i("FileUtils", "video or img type is ignore");
- return true;
- }
- File file = new File(filePath);
- if (!file.exists()) {
- Log.i("FileUtils", "file is not exist");
- return false;
- }
- int lastDot = file.getName().lastIndexOf(".");
- if (lastDot < 0) {
- Log.i("FileUtils", "lastDot is 0 isEmpty filetype");
- return false;
- }
- String type = file.getName().substring(lastDot + 1).toLowerCase();
- if (TextUtils.isEmpty(type)) {
- Log.i("FileUtils", "isEmpty filetype");
- return false;
- }
- if (TextUtils.equals(targetType, "midi")) {
- //兼容下mid格式
- return TextUtils.equals(type, "midi") || TextUtils.equals(type, "mid");
- }
- Log.i("FileUtils", "targetType:" + targetType + "-type:" + type);
- return TextUtils.equals(targetType, type);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return true;
- }
- public static boolean saveAudioToMusic(Context context, String filePath) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
- return saveAudioToMusicBeforeQ(context, filePath);
- } else {
- return saveAudioToMusicAfterQ(context, filePath);
- }
- }
- /**
- * 获取视频的contentValue
- */
- public static ContentValues getAudioContentValues(Context context, File paramFile, long timestamp) {
- ContentValues localContentValues = new ContentValues();
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
- localContentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM
- + File.separator + context.getPackageName());
- }
- localContentValues.put(MediaStore.Audio.Media.TITLE, paramFile.getName());
- localContentValues.put(MediaStore.Audio.Media.DISPLAY_NAME, paramFile.getName());
- localContentValues.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3");
- localContentValues.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/yyszkt");
- localContentValues.put(MediaStore.Audio.Media.DATE_TAKEN, timestamp);
- localContentValues.put(MediaStore.Audio.Media.DATE_MODIFIED, timestamp);
- localContentValues.put(MediaStore.Audio.Media.DATE_ADDED, timestamp);
- localContentValues.put(MediaStore.Audio.Media.SIZE, paramFile.length());
- localContentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
- localContentValues.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
- localContentValues.put(MediaStore.Audio.Media.IS_ALARM, false);
- localContentValues.put(MediaStore.Audio.Media.IS_MUSIC, false);
- return localContentValues;
- }
- private static boolean saveAudioToMusicAfterQ(Context context, String audioFilePath) {
- try {
- ContentResolver contentResolver = context.getContentResolver();
- File tempFile = new File(audioFilePath);
- ContentValues contentValues = getAudioContentValues(context, tempFile, System.currentTimeMillis());
- Uri uri = contentResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, contentValues);
- copyFileAfterQ(context, contentResolver, tempFile, uri);
- contentValues.clear();
- contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
- context.getContentResolver().update(uri, contentValues, null, null);
- context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- private static boolean saveAudioToMusicBeforeQ(Context context, String audioFile) {
- File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
- File tempFile = new File(audioFile);
- File destFile = new File(picDir, "yyszkt" + File.separator + tempFile.getName());
- FileInputStream ins = null;
- BufferedOutputStream ous = null;
- try {
- ins = new FileInputStream(tempFile);
- ous = new BufferedOutputStream(new FileOutputStream(destFile));
- long nread = 0L;
- byte[] buf = new byte[1024];
- int n;
- while ((n = ins.read(buf)) > 0) {
- ous.write(buf, 0, n);
- nread += n;
- }
- MediaScannerConnection.scanFile(
- context,
- new String[]{destFile.getAbsolutePath()},
- new String[]{"audio/*"},
- (path, uri) -> {
- // Scan Completed
- });
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- } finally {
- try {
- if (ins != null) {
- ins.close();
- }
- if (ous != null) {
- ous.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public static boolean saveVideoToGallery(Context context, String filePath) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
- return saveVideoToAlbumBeforeQ(context, filePath);
- } else {
- return saveVideoToAlbumAfterQ(context, filePath);
- }
- }
- private static boolean saveVideoToAlbumAfterQ(Context context, String videoFile) {
- try {
- ContentResolver contentResolver = context.getContentResolver();
- File tempFile = new File(videoFile);
- ContentValues contentValues = getVideoContentValues(context, tempFile, System.currentTimeMillis());
- Uri uri = contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
- copyFileAfterQ(context, contentResolver, tempFile, uri);
- contentValues.clear();
- contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
- context.getContentResolver().update(uri, contentValues, null, null);
- context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- /**
- * 获取视频的contentValue
- */
- public static ContentValues getVideoContentValues(Context context, File paramFile, long timestamp) {
- ContentValues localContentValues = new ContentValues();
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
- localContentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM
- + File.separator + context.getPackageName());
- }
- localContentValues.put(MediaStore.Video.Media.TITLE, paramFile.getName());
- localContentValues.put(MediaStore.Video.Media.DISPLAY_NAME, paramFile.getName());
- localContentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
- localContentValues.put(MediaStore.Video.Media.DATE_TAKEN, timestamp);
- localContentValues.put(MediaStore.Video.Media.DATE_MODIFIED, timestamp);
- localContentValues.put(MediaStore.Video.Media.DATE_ADDED, timestamp);
- localContentValues.put(MediaStore.Video.Media.SIZE, paramFile.length());
- return localContentValues;
- }
- private static void copyFileAfterQ(Context context, ContentResolver localContentResolver, File tempFile, Uri localUri) throws IOException {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
- context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.Q) {
- //拷贝文件到相册的uri,android10及以上得这么干,否则不会显示。可以参考ScreenMediaRecorder的save方法
- OutputStream os = localContentResolver.openOutputStream(localUri);
- Files.copy(tempFile.toPath(), os);
- os.close();
- // tempFile.delete();
- }
- }
- private static boolean saveVideoToAlbumBeforeQ(Context context, String videoFile) {
- File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
- File tempFile = new File(videoFile);
- File destFile = new File(picDir, context.getPackageName() + File.separator + tempFile.getName());
- FileInputStream ins = null;
- BufferedOutputStream ous = null;
- try {
- ins = new FileInputStream(tempFile);
- ous = new BufferedOutputStream(new FileOutputStream(destFile));
- long nread = 0L;
- byte[] buf = new byte[1024];
- int n;
- while ((n = ins.read(buf)) > 0) {
- ous.write(buf, 0, n);
- nread += n;
- }
- MediaScannerConnection.scanFile(
- context,
- new String[]{destFile.getAbsolutePath()},
- new String[]{"video/*"},
- (path, uri) -> {
- // Scan Completed
- });
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- } finally {
- try {
- if (ins != null) {
- ins.close();
- }
- if (ous != null) {
- ous.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 删除文件
- *
- * @param path
- */
- public static void deleteFile(String path) {
- if (TextUtils.isEmpty(path)) {
- return;
- }
- File file = new File(path);
- deleteFile(file);
- }
- /**
- * 获取文件后缀类型根据url
- * @param url
- * @return
- */
- public static String getFileTypeFromUrl(String url) {
- try {
- URL url1 =new URL(url);
- String path = url1.getPath();
- if (path.contains("?")) {
- String[] split = path.split("\\?");
- path = split[0];
- }
- int lastDot = path.lastIndexOf(".");
- if (lastDot < 0) {
- return "";
- }
- String type = path.substring(lastDot + 1).toLowerCase();
- return type;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return "";
- }
- public static boolean clearMusicMergeCache() {
- try {
- String material = FileUtils.getCacheDir(Utils.getApp(), "musicmerge");
- FileUtils.deleteAllInDir(material);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return false;
- }
- }
|