Android_應用層_File封裝讀寫儲存
阿新 • • 發佈:2019-02-09
開篇介紹:
其實這邊文章是之前SP,SQlite儲存的最後一篇,也就是Android的3種儲存方式(當然不包括記憶體啦),File檔案儲存,對於快取歷史資訊和使用者一些可公開資訊,例如網上的縮圖,小視訊等等,SDCard儲存還是很有必要的,這篇完成,應用層儲存的也就結束了。
廢話不多說,直接上程式碼,大家可以參考指正
package com.huawei.genexcloud.base.framework.utils; import android.content.Context; import android.content.res.AssetManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Environment; import android.os.StatFs; import com.huawei.genexcloud.base.framework.log.GCLogger; import com.huawei.genexcloud.base.framework.log.Module; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; 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.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.text.DecimalFormat; import java.text.Normalizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** *@author zhanglong ****2016-3-20 ***/ public class FileUtil { public static final int MIN_AVAILABLE_SIZE = 100; private static final int ONE_KILO_BYTES = 1024; private static final int ONE_MEGA_BYTES = 1024 * 1024; /** * 判斷SDcard是否可用, 已經掛載並且擁有可讀可寫許可權 true 可用 */ public static boolean ifSDcardMounted() { String path = "/HWUserData"; File file = new File(path); if (file.exists()) { if (!file.canWrite()) { return false; } StatFs sf = new StatFs(file.getPath()); long availCount = sf.getAvailableBlocks(); return availCount > 0; } else { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } } /** * 建立資料夾 * * @throws IOException */ public static boolean createDirector(String directorFilePath) { if (null == directorFilePath) { return false; } String[] dirStructure = parseDirStructure(directorFilePath); File file; boolean isSucceed = true; for (int i = 0; i < dirStructure.length; i++) { file = new File(dirStructure[i]); if (!file.exists()) { isSucceed = (isSucceed && file.mkdir()); if (i == dirStructure.length - 1) { return isSucceed; } } } return false; } /** * 移動資源配置檔案至制定路徑 */ public static void writeResToPhone(Context context, String fileName, int res) { InputStream inputStream = null; FileOutputStream outputStream = null; try { if (isFileExist(fileName)) { return; } createFile(fileName); inputStream = context.getResources().openRawResource(res); outputStream = new FileOutputStream(fileName); write(inputStream, outputStream); } catch (FileNotFoundException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeResToPhone(res) Exception"); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeResToPhone(res) IOException"); } finally { IOUtil.closeInputStream(inputStream); IOUtil.closeOutputStream(outputStream); } } /** * 移動Assets目錄下的檔案 */ public static boolean writeAssetToPhone(Context context, String assetPath, String dir) { File file = new File(dir); if (!file.exists()) { file.mkdir(); } String[] fileList = getAllFiles(dir); if (null != fileList) { if (fileList.length != 0) { return true; } } AssetManager assetManager = context.getAssets(); if (!dir.endsWith("/")) { dir += File.separator; } String[] files; try { files = assetManager.list(assetPath); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]writeAssetToPhone(dir) IOException"); return false; } return writeFiles(assetPath, dir, assetManager, files); } public static String read(String assetsPath, Context context) { BufferedReader reader = null; InputStream in = null; StringBuffer bufferContent = new StringBuffer(); String lineContent; try { in = context.getAssets().open(assetsPath); reader = new BufferedReader(new InputStreamReader(in)); while ((lineContent = reader.readLine()) != null) { bufferContent.append(lineContent); } return bufferContent.toString(); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]readFileByLine() IOException"); } finally { IOUtil.closeInputStream(in); IOUtil.closeReader(reader); } return ""; } private static boolean writeFiles(String assetPath, String dir, AssetManager assetManager, String[] files) { boolean isSuccess = false; for (String strSvy : files) { String filePath = assetPath + File.separator + strSvy; InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = assetManager.open(filePath); outputStream = new FileOutputStream(dir + strSvy); isSuccess = write(inputStream, outputStream); } catch (FileNotFoundException e) { GCLogger.error(Module.FILE_MANAGER, "[FileUtil] writeAssetToPhone(dir) for{} Exception"); isSuccess = false; } catch (IOException e) { GCLogger.error(Module.FILE_MANAGER, "[FileUtil]writeAssetToPhone(dir) for{} IOException"); isSuccess = false; } finally { IOUtil.closeInputStream(inputStream); IOUtil.closeOutputStream(outputStream); } } return isSuccess; } private static boolean write(InputStream inputStream, OutputStream outputStream) throws IOException { int count; byte[] buffer = new byte[1024]; while ((count = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, count); } outputStream.flush(); return true; } public static void writeContinueContent(String path, String conent) { BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(path, true))); out.write(conent); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void closeRandomAccessFile(RandomAccessFile randomAccessFile) { if (null != randomAccessFile) { try { randomAccessFile.close(); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] closeRandomAccessFile() IOException"); } } } /** * 建立檔案,fileName為檔案全路徑加檔名 */ public static boolean createFile(String fileName) { String[] dirStructure = parseDirStructure(fileName); File file; for (int i = 0; i < dirStructure.length; i++) { file = new File(dirStructure[i]); if (i == dirStructure.length - 1) { if (!file.isFile()) { return createNewFile(file); } } else { makeFileDirectory(file); } } return false; } /** * 通過提供的檔名在預設路徑下生成檔案 * * @param fileName 檔案的名稱 * @return 生成的檔案 */ public static File createFileByName(String fileName) { File file = new File(fileName); if (!isFileExist(file)) { try { file.createNewFile(); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]" + e.toString()); } } return file; } /** * 是否存在此檔案 * * @param file 判斷是否存在的檔案 * @return 存在返回true,否則返回false */ public static boolean isFileExist(final File file) { // 在無SD卡時file會為空 if (file == null) { return false; } if (file.exists()) { return true; } else { return false; } } private static void makeFileDirectory(File file) { if (!file.exists()) { boolean isCreateFileDirectorySuccess = file.mkdir(); if (!isCreateFileDirectorySuccess) { GCLogger.error(Module.UTILITIES, new StringBuffer("[FileUtil] : makeFileDirectory(File file), ") .append("Make directory failed!").toString()); } } } /** * 刪除標準檔案 */ public static boolean deleteFile(String fileName) { return isFileExist(fileName) && (new File(fileName).delete()); } private static boolean deleteFile(File file) { return file.exists() && file.delete(); } /** * 刪除某個目錄下的所有檔案,但不刪除該目錄 */ public static boolean deleteFiles(File dir) { if (null == dir) { return false; } if (!dir.isDirectory()) { return deleteFile(dir); } boolean isSucceed = true; File[] files = dir.listFiles(); if (null != files) { for (File file : files) { isSucceed &= deleteFiles(file); } } return isSucceed; } public static boolean deleteDir(File dir) { if (!dir.isDirectory()) { return deleteFile(dir); } boolean isSucceed = true; File[] files = dir.listFiles(); if (null != files) { for (File file : files) { isSucceed &= deleteDir(file); } } isSucceed &= dir.delete(); return isSucceed; } /** * @param context * @param srcName The name of the file to open; can not contain path separators. * @param dest */ public static void copyFile(Context context, String srcName, String dest) { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = context.openFileInput(srcName); File file = new File(dest); if (!file.exists()) { file.createNewFile(); } outputStream = new FileOutputStream(dest); write(inputStream, outputStream); } catch (FileNotFoundException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] copyFile(src)Exception"); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] copyFile(src)IOException"); } finally { IOUtil.closeInputStream(inputStream); IOUtil.closeOutputStream(outputStream); } } public static void copyFile(String src, String dest) { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(src)); File file = new File(dest); if (!file.exists()) { file.createNewFile(); } outputStream = new FileOutputStream(dest); write(inputStream, outputStream); } catch (FileNotFoundException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] copyFile()Exception"); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] copyFile()IOException"); } finally { IOUtil.closeInputStream(inputStream); IOUtil.closeOutputStream(outputStream); } } public static boolean isFileExist(String filePath) { if (null == filePath) { return false; } File file = new File(filePath); return file.isFile(); } private static boolean createNewFile(File file) { try { return file.createNewFile(); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] createNewFile()IOException"); return false; } } public static boolean isNoSpaceLeft(String root) { return getAvailableFileSize(root) < MIN_AVAILABLE_SIZE; } /** * 判斷空間是否足夠 >100M */ public static boolean isEnoughSpaceLeft(String root, int fileSize) { long spaceLeft = getAvailableFileSize(root); return spaceLeft * ONE_KILO_BYTES > (long) fileSize * ONE_MEGA_BYTES; } public static long getAvailableFileSize(String root) { try { StatFs statFs = new StatFs(root); long blockSize = statFs.getBlockSize(); long availableBlocks = statFs.getAvailableBlocks(); return blockSize * availableBlocks / 1024; } catch (IllegalArgumentException e) { GCLogger.error(Module.UTILITIES, new StringBuffer("[FileUtil] getAvailableFileSize()Exception").toString()); return Long.MAX_VALUE; } } public static ArrayList<String> searchFileToString(String path, String postfix) { path = Normalizer.normalize(path, Normalizer.Form.NFKC); if (!path.endsWith("/")) { path = path + "/"; } ArrayList<String> fileToString = new ArrayList<String>(); File file = new File(path); if (!file.exists() || !file.isDirectory()) { return fileToString; } File[] files = file.listFiles(); if (null != files) { addFileNameToList(path, postfix, fileToString, files); } return fileToString; } private static void addFileNameToList(String path, String postfix, ArrayList<String> fileToString, File[] files) { for (File file1 : files) { if (file1.isFile()) { String name = file1.getName(); if (name.endsWith(postfix)) { fileToString.add(path + file1.getName()); } } } } private static String[] parseDirStructure(String remotePathName) { ArrayList<String> dirList = new ArrayList<String>(); String path = remotePathName; int index = 0; for (int i = 0; i < path.length(); i++) { if (path.charAt(i) == '/' && i > 0) { dirList.add(path.substring(0, i)); index = i; } } if (index < path.length()) { dirList.add(path.substring(0, path.length())); } String[] retStr = new String[dirList.size()]; return dirList.toArray(retStr); } public static String formatFilePath(String filePath) { if (!filePath.endsWith("/")) { filePath += File.separator; } return filePath; } public static String[] getAllFiles(String remotePathName) { File file = new File(remotePathName); if (!file.isDirectory()) { return new String[0]; } return file.list(); } public static File[] getFiles(File dir, FilenameFilter filenameFilter) { if (!dir.isDirectory()) { return new File[0]; } return dir.listFiles(filenameFilter); } public static File getFile(String path) { File file = new File(path); if (!file.isDirectory()) { return file; } return null; } /** * 檢查記錄檔案的大小 */ public static int getFileCurrentSize(File file) { return (int) ((file.length() + 1024) / 1024);// kb } /** * 獲取執行路徑下的所有檔案列表,按最後修改時間排序 */ public static List<String> getAllFilesByLastModifyTime(String remotePathName) { List<String> allFilesName = new ArrayList<String>(); File file = new File(remotePathName); if (!file.isDirectory()) { return new ArrayList<String>(); } File[] fileList = file.listFiles(); if (null != fileList) { // 按照檔案最後修改時間排序 sortFiles(fileList); for (File f : fileList) { if (f.getAbsoluteFile().isFile()) { allFilesName.add(f.getName()); } } } return allFilesName; } private static void sortFiles(File[] fileList) { Arrays.sort(fileList, new Comparator<File>() { @Override public int compare(File o1, File o2) { if (o1.lastModified() < o2.lastModified()) { return 1; } else if (o1.lastModified() == o2.lastModified()) { return 0; } else { return -1; } } }); } public static String getDefaultFileName(String mIMEI) { String strFileName = mIMEI + "_" + getCurrentTime(); return strFileName; } public static String getCurrentTime() { DecimalFormat df = new DecimalFormat("00"); Calendar c = Calendar.getInstance(); String currentTime = c.get(Calendar.YEAR) + df.format((c.get(Calendar.MONTH) + 1)) + df.format(c.get(Calendar.DAY_OF_MONTH)) + df.format(c.get(Calendar.HOUR_OF_DAY)) + df.format(c.get(Calendar.MINUTE)) + df.format(c.get(Calendar.SECOND)); return currentTime; } public static long getDirTotalSize(String rootDir) { File dir = new File(rootDir); File[] files = dir.listFiles(); if (null == files) { return 0; } long chrFileLen = 0; for (File file : files) { chrFileLen += file.length(); } return chrFileLen; } public static String getFileName(String filePath) { if (null == filePath) { return null; } filePath = pathFilter(filePath); int end = filePath.lastIndexOf("."); int start = filePath.lastIndexOf("/"); return filePath.substring(start + 1, end); } public static String getFileFullName(String filePath) { if (null == filePath) { return null; } filePath = pathFilter(filePath); int start = filePath.lastIndexOf("/"); return filePath.substring(start + 1); } public static String pathFilter(String path) { path = path.replace(" ", ""); path = path.replace("\\", "/"); while (path.indexOf("//") != -1) { path = path.replace("//", "/"); } return path; } public static void renameFile(String oldname, String newname) { if (!oldname.equals(newname)) { File oldfile = new File(oldname); File newfile = new File(newname); renameFile(oldfile, newfile); } } public static void renameFile(String path, String oldname, String newname) { if (!oldname.equals(newname)) { File oldfile = new File(oldname); File newfile = new File(newname); renameFile(oldfile, newfile); } } private static boolean renameFile(File oldfile, File newfile) { // 若在該目錄下已經有一個檔案和新檔名相同,則不允許重新命名 return !newfile.exists() && oldfile.renameTo(newfile); } public static byte[] readFile(File file) { if (null == file || !file.isFile()) { return null; } ByteArrayOutputStream outputStream = null; InputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); outputStream = new ByteArrayOutputStream(1024); write(inputStream, outputStream); byte[] bytes = outputStream.toByteArray(); return bytes; } catch (FileNotFoundException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] readFile(byte)Exception"); return null; } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] readFile(byte)IOException"); return null; } finally { IOUtil.closeOutputStream(outputStream); IOUtil.closeInputStream(inputStream); } } public static boolean writeFile(byte[] value, File file) { if (null == value) { return false; } BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); out.write(value); return true; } catch (FileNotFoundException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeFile(boolean)Exception"); FileUtil.deleteDir(file); return false; } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeFile(boolean)IOException"); FileUtil.deleteDir(file); return false; } finally { IOUtil.closeOutputStream(out); } } public static boolean writeToAndroid(String srcFilePath, String destFileName, Context context) { InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(srcFilePath); outputStream = context.openFileOutput(destFileName, Context.MODE_PRIVATE); write(inputStream, outputStream); return true; } catch (FileNotFoundException fe) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeToAndroid()Exception Exception"); return false; } catch (IOException ie) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeToAndroid()IOException"); return false; } finally { IOUtil.closeInputStream(inputStream); IOUtil.closeOutputStream(outputStream); } } public static boolean isDirectoryExist(String path) { File file = new File(path); return file.isDirectory(); } public static void delAllExpiredFile(String path, int validPeriod) { File file = new File(path); File[] files = file.listFiles(new NoDirFileFilter()); if (null != files) { for (File file1 : files) { if (isFileExpired(file1, validPeriod)) { deleteFile(file1); } } } } private static boolean isFileExpired(File file, int validPeriod) { if (!file.isFile()) { return false; } return TimeUtil.isExpired(file.lastModified(), System.currentTimeMillis(), validPeriod); } static class NoDirFileFilter implements FileFilter { @Override public boolean accept(File file) { return file.isFile(); } } public static LinkedList<File> convertFileArrayToList(File[] files) { LinkedList<File> fileList = new LinkedList<File>(); if (files.length > 0) { for (File file : files) { fileList.add(file); } } return fileList; } public static String readFileOnlyOneLine(File file) { BufferedReader reader = null; String lineContent = null; if (validateFile(file)) { try { reader = new BufferedReader(new FileReader(file)); lineContent = reader.readLine(); } catch (FileNotFoundException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]readFileOnlyOneLine() Exception"); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] readFileOnlyOneLine() IOException"); } finally { IOUtil.closeReader(reader); } } return lineContent; } public static String readFileByLine(File file) { StringBuffer bufferContent = new StringBuffer(); if (validateFile(file)) { BufferedReader reader = null; String lineContent; try { reader = new BufferedReader(new FileReader(file)); while ((lineContent = reader.readLine()) != null) { bufferContent.append(lineContent + "\n"); } } catch (FileNotFoundException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]readFileByLine() Exception"); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]readFileByLine() IOException"); } finally { IOUtil.closeReader(reader); } } return bufferContent.toString(); } /** * 讀取assets文字 * * @param assetsName * @return */ public static String readAssetsString(Context context, String assetsName) { StringBuilder stringBuilder = new StringBuilder(); try { BufferedReader bf = new BufferedReader( new InputStreamReader(context.getAssets().open(assetsName), "UTF-8")); String line; while ((line = bf.readLine()) != null) { stringBuilder.append(line); } } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } public static String readFileWithoutLine(String path) { File file = new File(path); StringBuffer bufferContent = new StringBuffer(); if (validateFile(file)) { BufferedReader reader = null; String lineContent; try { reader = new BufferedReader(new FileReader(file)); while ((lineContent = reader.readLine()) != null) { bufferContent.append(lineContent); } } catch (FileNotFoundException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]readFileByLine() Exception"); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]readFileByLine() IOException"); } finally { IOUtil.closeReader(reader); } } return bufferContent.toString(); } public static void writeFile(File file, String content) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(file)); writer.write(content); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeFile()IOException"); } finally { IOUtil.closeWriter(writer); } } public static void writeFileContinue(File file, String content) { BufferedWriter bufferedWriter = null; FileWriter fileWriter = null; try { fileWriter = new FileWriter(file, true); bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(content); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeFileContinue()IOException"); } catch (OutOfMemoryError e) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeFileContinue()Error"); } finally { IOUtil.closeWriter(bufferedWriter); IOUtil.closeWriter(fileWriter); } } public static void writeContent(BufferedWriter writer, String content) { if (null == writer) { return; } try { writer.write(content); writer.newLine(); writer.flush(); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil] writeContent()IOException"); } } public static void createFileWithConstContent(String fileName, int fileSize) { if (fileSize <= 0) { return; } createFile(fileName); BufferedOutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(new File(fileName))); byte[] oneKBytes = new byte[ONE_KILO_BYTES]; for (int i = 0; i < fileSize; i++) { outputStream.write(oneKBytes); outputStream.flush(); } } catch (FileNotFoundException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]createFileWithConstContent() Exception"); } catch (IOException e) { GCLogger.error(Module.UTILITIES, "[FileUtil]createFileWithConstContent() IOException"); } finally { IOUtil.closeOutputStream(outputStream); } } private static boolean validateFile(File file) { return file.exists() && file.isFile(); } public static String getApkAboutInformation(String path, String defaultStr) { File buildTimeFile = new File(path); String content = readFileOnlyOneLine(buildTimeFile); return null == content ? defaultStr : content; } public static boolean moveOrRewriteFile(String src, String dest) { if (!isFileExist(src)) { return false; } if (isFileExist(dest)) { deleteFile(dest); } copyFile(src, dest); deleteFile(src); return true; } public static long getFileSize(Module module, File file) { if (file.exists()) { return file.length(); } else { // GCLogger.debug("module", "File is not exist!"); } return 0; } public static void clearData(FileInputStream inputStream, byte[] readBuffer) { try { long fileSize; do { fileSize = inputStream.read(readBuffer); if (fileSize <= 0) { return; } } while (fileSize == readBuffer.length); } catch (IOException e) { GCLogger.error(Module.DIAG_MANAGER, "[FileUtil] clearData()IOException"); } } /** * 檢查SD卡是否存在 * * @return 是否存在 */ public static boolean isSdCardAvailable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } /** * 檔案或資料夾是否存在 */ public static boolean isFileOrPathExist(String filePath) { if (null == filePath) { return false; } File file = new File(filePath); return file.exists(); } /** * 獲取檔名,區分大小寫 **/ public static String getFileNameIgnoreCase(String fileName, String directory) { if (null == directory) { return null; } String[] fileList = FileUtil.getAllFiles(directory); if (null == fileList) { return null; } for (int i = 0; i < fileList.length; i++) { if (fileName.equalsIgnoreCase(fileList[i])) { return fileList[i]; } } return null; } public static List<String> getAllFile(File root) { List<String> fileList = new ArrayList<String>(); File files[] = root.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { getAllFile(file); } else { if (file.toString().endsWith("png") || file.toString().endsWith("PNG")) { fileList.add(file.getName()); } } } } return fileList; } //得到該目錄下所有後綴是.txt的檔名 public static List<String> getAllTxtFileNameForDir(File dir) { List<String> fileList = new ArrayList<>(); File[] files = dir.listFiles(); if (null != files) { for (File file : files) { if (file.toString().endsWith(".txt")) { fileList.add(file.getName()); } } } return fileList; } /** * 獲取外掛化 資料夾路徑 的公用方法 * * @return */ public static String getPluginGlobalDir() { String pluginsDir = getPublicDataRootDir() + "/plugins/"; File fileDir = new File(pluginsDir); if (!fileDir.exists()) { boolean mkdir = fileDir.mkdirs(); } return pluginsDir; } /** * 獲取外掛化 資料夾temp路徑 的公用方法 * * @return */ public static String getPluginTempDir() { String pluginsDir = getPublicDataRootDir() + "/plugins/temp/"; File fileDir1 = new File(pluginsDir); if (!fileDir1.exists()) { boolean mkdir = fileDir1.mkdirs(); } return pluginsDir; } /** * 此方法用於修改儲存路徑的公用介面 * * @return */ public static String getPublicDataRootDir() { return EnvironmentInfo.getDataRootDirectory(); //return EnvironmentInfo.getProductFileDirectory(); } /** * 獲取圖片本地地址 * * @param context * @param imageID * @return */ public static String getIconAddress(Context context, int imageID) { Resources res = context.getResources(); BitmapDrawable d = (BitmapDrawable) res.getDrawable(imageID); Bitmap img = d.getBitmap(); String fn = imageID + ".PNG"; String path = FileUtil.getPluginTempDir() + fn; try { OutputStream os = new FileOutputStream(path); //把bitmap壓縮成png img.compress(Bitmap.CompressFormat.PNG, 100, os); os.close(); return path; } catch (Exception e) { return ""; } } }