總結一波文件操做相關的共通方法(拿來就用)android
須要申請的權限:app
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
1.獲取文件夾下的全部文件名ide
public static List<String> getFileName(String fileName) { List<String> fileList = new ArrayList<>(); File file = new File(fileName); if (!file.exists()) { return null; } File f[] = file.listFiles(); for (int i = 0; i < f.length; i++) { File fs = f[i]; if (!fs.isDirectory()) { fileList.add(fs.getName()); } } return fileList; }
2.在SD卡上建立文件ui
public static File createFile(String fileName) throws IOException { File file = new File(fileName); if (!isFileExists(file)) { if (file.isDirectory()) { file.mkdirs(); } else { file.createNewFile(); } } return file; }
3.在SD卡上建立文件夾google
public static File createFolder(String fileName) throws IOException { File file = new File(fileName); if (!isFileExists(file)) { file.mkdirs(); } return file; }
4.讀取SD卡中文本文件spa
public synchronized static String readFile(String fileName) { StringBuffer sb = new StringBuffer(); File file = new File(fileName); String str = null; try { InputStream is = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); @SuppressWarnings("resource") BufferedReader reader = new BufferedReader(isr); while ((str = reader.readLine()) != null) { sb.append(str); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); }
5.刪除單個文件code
public static boolean deleteFile(String filePath) { File file = new File(filePath); if (file.isFile() && file.exists()) { return file.delete(); } return false; }
filePath 被刪除文件的文件名blog
return 文件刪除成功返回true,不然返回false。rem
6.刪除文件夾以及其目錄下的文件get
public static boolean deleteFolder(String filePath) { boolean flag = false; // 若是filePath不以文件分隔符結尾,自動添加文件分隔符 if (!filePath.endsWith(File.separator)) { filePath = filePath + File.separator; } File dirFile = new File(filePath); if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } flag = true; File[] files = dirFile.listFiles(); // 遍歷刪除文件夾下的全部文件(包括子目錄) for (File file : files) { if (file.isFile()) { // 刪除子文件 flag = deleteFile(file.getAbsolutePath()); if (!flag) break; } else { // 刪除子目錄 flag = deleteFolder(file.getAbsolutePath()); if (!flag) break; } } if (!flag) return false; // 刪除當前空目錄 return dirFile.delete(); }
filePath 被刪除目錄的文件路徑
return 目錄刪除成功返回true,不然返回false
7.把文件轉換成Base64
public static String encodeBase64File(String path) throws Exception { byte[] videoBytes; ByteArrayOutputStream baos = new ByteArrayOutputStream(); @SuppressWarnings("resource") FileInputStream fis = new FileInputStream(new File(path)); byte[] buf = new byte[1024]; int n; while (-1 != (n = fis.read(buf))) { baos.write(buf, 0, n); } videoBytes = baos.toByteArray(); return Base64.encodeToString(videoBytes, Base64.NO_WRAP); }
8.根據相冊媒體庫路徑轉換成SD卡路徑(Android 4.4以上)
@TargetApi(Build.VERSION_CODES.KITKAT) public static String getPath(final Context context, final Uri uri) { final boolean isOverKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isOverKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[]{split[1]}; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; }
上面方法可能須要下列輔助方法的支持:
public static boolean isFileExists(File file) { return file.exists(); }
public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); }
public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); }
public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); }
public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); }
@SuppressLint("NewApi") public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = {column}; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int index = cursor.getColumnIndexOrThrow(column); return cursor.getString(index); } } finally { if (cursor != null) cursor.close(); } return null; }
長期更新,未完待續。。。