【方法总结】创建、读取、删除文件相关操作

 总结一波文件操作相关的共通方法(拿来就用)

 需要申请的权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 

 1.获取文件夹下的所有文件名

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卡上创建文件

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卡上创建文件夹

public static File createFolder(String fileName) throws IOException {
    File file = new File(fileName);
    if (!isFileExists(file)) {
        file.mkdirs();
    }
    return file;
}

 

 4.读取SD卡中文本文件

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.删除单个文件

public static boolean deleteFile(String filePath) {
    File file = new File(filePath);
    if (file.isFile() && file.exists()) {
        return file.delete();
    }
    return false;
}

 filePath 被删除文件的文件名

 return 文件删除成功返回true,否则返回false。

 

 6.删除文件夹以及其目录下的文件

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;
}

 

 长期更新,未完待续。。。

 

posted on 2017-04-26 11:58  Tyhoo_Wu  阅读(817)  评论(0编辑  收藏  举报

导航