[Method summary] operations related to file creation, reading, and deletion, and reading and deleting
Summarize the common methods related to a wave of File Operations (for use)
Required permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
1. Get all file names in the folder
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. Create a file on the SD card
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. Create a folder on the SD card
public static File createFolder(String fileName) throws IOException { File file = new File(fileName); if (!isFileExists(file)) { file.mkdirs(); } return file;}
4. Read text files from the SD card
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. delete a single file
public static boolean deleteFile(String filePath) { File file = new File(filePath); if (file.isFile() && file.exists()) { return file.delete(); } return false;}
File Name of the deleted file in filePath
Return true if the file is successfully deleted; otherwise, false is returned.
6. delete folders and files in their directories
Public static boolean deleteFolder (String filePath) {boolean flag = false; // if filePath does not end with a file separator, the file separator 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 (); // traverse and delete all files (including subdirectories) in the folder for (File file: files) {if (file. isFile () {// Delete the sub-file flag = deleteFile (file. getAbsolutePath (); if (! Flag) break;} else {// Delete sub-directory flag = deleteFolder (file. getAbsolutePath (); if (! Flag) break;} if (! Flag) return false; // delete the empty current directory return dirFile. delete ();}
FilePath: the file path of the deleted directory
Return true if the return directory is successfully deleted; otherwise, false is returned.
7. Convert the file to 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. Convert the path from the photo album Library to the SD card path (Android 4.4 or above)
@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;}
The preceding method may require the support of the following auxiliary methods:
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;}
It has been updated for a long time and is not yet resumed...