import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import androidx.core.content.FileProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* 文件管理工具类
*/
public class FileManagerUtils {
private final String TAG = "FileManagerUtils";
private static Context mContext;
private static FileManagerUtils instance;
public static final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR";
private MediaScanner mMediaScanner;
/**
* 文档类型
*/
public static final int TYPE_DOC = 0;
/**
* apk类型
*/
public static final int TYPE_APK = 1;
/**
* 压缩包类型
*/
public static final int TYPE_ZIP = 2;
/**
* 视频类型
*/
public static final int TYPE_VIDEO = 3;
/**
* 图片类型
*/
public static final int TYPE_IMG = 4;
/**
* 音乐类型
*/
public static final int TYPE_MUSIC = 5;
/**
* 未知类型
*/
public static final int TYPE_UNKNOW = -1;
public static FileManagerUtils getInstance(Context context) {
if (instance == null) {
instance = new FileManagerUtils(context);
}
mContext = context;
return instance;
}
public FileManagerUtils(Context context) {
this.mContext = context;
mMediaScanner = new MediaScanner(context);
}
/**
* 获取全部图片文件
*
* @return 取全部图片文件
*/
public List<FileIconBean> getAllImgFileList() {
List<FileIconBean> mList = new ArrayList<>();
if (mContext != null) {
Cursor cursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null,
null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
int id = cursor
.getInt(cursor
.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
String title = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE));
String path = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
String displayName = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
String mimeType = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE));
long size = cursor
.getLong(cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
FileIconBean mIconBean = new FileIconBean();
mIconBean.setMime_type(mimeType);
mIconBean.setFile_type(CommonConst.FILE_TYPE_IMG);
mIconBean.setFile_name(displayName);
mIconBean.setFile_path(path);
mIconBean.setDirectory(false);
mIconBean.setSize(size);
mList.add(mIconBean);
}
cursor.close();
}
}
Log.d(TAG, " get All image file " + mList.toString());
return mList;
}
/**
* 获取所有视频文件
*
* @return
*/
public List<FileIconBean> getAllVideoFileList() {
List<FileIconBean> mList = new ArrayList<>();
if (mContext != null) {
Cursor cursor = mContext.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null,
null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
String title = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
String album = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.ALBUM));
String artist = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.ARTIST));
String displayName = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
String mimeType = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
String path = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
long size = cursor
.getLong(cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
FileIconBean mIconBean = new FileIconBean();
mIconBean.setMime_type(mimeType);
mIconBean.setFile_type(CommonConst.FILE_TYPE_VIDEO);
mIconBean.setFile_name(displayName);
mIconBean.setFile_path(path);
mIconBean.setDirectory(false);
mIconBean.setSize(size);
mList.add(mIconBean);
}
cursor.close();
}
}
Log.d(TAG, " get All video file " + mList.toString());
return mList;
}
/**
* 获取全部图片文件
*
* @return 取全部图片文件
*/
@TargetApi(Build.VERSION_CODES.Q)
public List<FileIconBean> getAllDownloadFileList() {
List<FileIconBean> mList = new ArrayList<>();
if (mContext != null) {
Cursor cursor = mContext.getContentResolver().query(
MediaStore.Downloads.EXTERNAL_CONTENT_URI, null, null,
null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
int id = cursor
.getInt(cursor
.getColumnIndexOrThrow(MediaStore.Downloads._ID));
String title = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Downloads.TITLE));
String path = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Downloads.DATA));
String displayName = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Downloads.DISPLAY_NAME));
String mimeType = cursor
.getString(cursor
.getColumnIndexOrThrow(MediaStore.Downloads.MIME_TYPE));
long size = cursor
.getLong(cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
FileIconBean mIconBean = new FileIconBean();
mIconBean.setMime_type(mimeType);
mIconBean.setFile_type(CommonConst.FILE_TYPE_IMG);
mIconBean.setFile_name(displayName);
mIconBean.setFile_path(path);
mIconBean.setDirectory(false);
mIconBean.setSize(size);
mList.add(mIconBean);
}
cursor.close();
}
}
Log.d(TAG, " get All image file " + mList.toString());
return mList;
}
/**
* 复制单个文件
*
* @param oldPath$Name String 原文件路径+文件名 如:data/user/0/com.test/files/abc.txt
* @param newPath$Name String 复制后路径+文件名 如:data/user/0/com.test/cache/abc.txt
* @return <code>true</code> if and only if the file was copied;
* <code>false</code> otherwise
*/
public boolean copyFile(String oldPath$Name, String newPath$Name, String fileName) {
boolean copySuccess = false;
try {
File oldFile = new File(oldPath$Name);
if (!oldFile.exists()) {
Log.e(TAG, "copyFile: oldFile not exist.");
return false;
} else if (!oldFile.isFile()) {
Log.e(TAG, "copyFile: oldFile not file.");
return false;
} else if (!oldFile.canRead()) {
Log.e(TAG, "copyFile: oldFile cannot read.");
return false;
}
FileInputStream fileInputStream = new FileInputStream(oldPath$Name); //读入原文件
FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name + "/" + fileName);
byte[] buffer = new byte[1024];
int byteRead;
while ((byteRead = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, byteRead);
}
fileInputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
copySuccess = true;
} catch (Exception e) {
e.printStackTrace();
BufferedReader input = null;
try {
Process p = Runtime.getRuntime().exec("cp -r " + oldPath$Name + " " + newPath$Name);
input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
input.close();
} catch (IOException ex) {
Log.e(TAG, "Unable to read prop " + oldPath$Name, ex);
copySuccess = false;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ioe) {
ioe.printStackTrace();
copySuccess = false;
}
}
}
}
if (getFileType(newPath$Name + "/" + fileName) == TYPE_IMG
|| getFileType(newPath$Name + "/" + fileName) == TYPE_VIDEO) {
Log.d(TAG, "当前复制的是媒体文件 ");
//scanFileAsync(newPath$Name + "/" + fileName);
File scanDir = new File(newPath$Name + "/" + fileName + "/");
if (scanDir.exists()) {
mMediaScanner.scanFile(scanDir, "");
}
}
return copySuccess;
}
/**
* 使用命令cp -r进行文件夹拷贝
*
* @param olderPath
* @param newPath
* @return
*/
public synchronized boolean copyByCmdFolder(String olderPath, String newPath) {
Log.d(TAG, " copyByCmdFolder " + olderPath + " new path is " + newPath);
BufferedReader input = null;
try {
Process p = Runtime.getRuntime().exec("cp -r " + olderPath + " " + newPath + "/");
input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
input.close();
} catch (IOException ex) {
Log.e(TAG, "Unable to read prop " + olderPath, ex);
return false;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
// scanDirAsync(newPath);
File scanDir = new File(newPath + "/");
if (scanDir.exists()) {
mMediaScanner.scanFile(scanDir, "");
}
return true;
}
/**
* 创建目录,在当前目录下
*
* @param currentPath
* @param name
* @return
*/
public synchronized boolean mkDirectory(String currentPath, String name) {
Log.d(TAG, "新增文件夹... 路径是" + currentPath + " 名称为" + name);
File file = new File(currentPath + "/" + name);
boolean ret = false;
if (file.exists()) {
Log.d(TAG, "不允许重复添加,当前文件夹已存在!");
ret = false;
} else {
ret = file.mkdirs();
}
return ret;
}
/**
* 使用cmd rm -rf 删除对应文件路径
*
* @param path 路径全称
* @return
*/
public synchronized boolean deleteByCmd(String path) {
//path = "\"" + path + "\"";
// path = path.replace(" ", "\\ ");
Log.d(TAG, "使用命令rm -rf删除文件路径 ");
boolean ret = true;
File file = new File(path);
if (file.exists()) {
if (file.isDirectory()) { //文件夹采用rm -rf 删除方式
BufferedReader input = null;
try {
Process p = Runtime.getRuntime().exec("rm -rf " + path);
input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
input.close();
} catch (IOException ex) {
ex.printStackTrace();
ret = false;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
ret = false;
}
}
}
} else {
ret = file.delete();
}
} else {
Log.d(TAG, "文件不存在");
}
if (file.exists()) {
mMediaScanner.scanFile(file, "");
}
return ret;
}
/**
* 根据文件路径获取文件类型
*
* @param path
* @return
*/
public static int getFileType(String path) {
path = path.toLowerCase();
if (path.endsWith(".doc") || path.endsWith(".docx") || path.endsWith(".xls") || path.endsWith(".xlsx")
|| path.endsWith(".ppt") || path.endsWith(".pptx")) {
return TYPE_DOC;
} else if (path.endsWith(".apk")) {
return TYPE_APK;
} else if (path.endsWith(".zip")
|| path.endsWith(".rar")
|| path.endsWith(".tar")
|| path.endsWith(".gz")) {
return TYPE_ZIP;
} else if (path.endsWith(".3g2")
|| path.endsWith(".3gp")
|| path.endsWith(".asf")
|| path.endsWith(".avi")
|| path.endsWith(".flv")
|| path.endsWith(".m4v")
|| path.endsWith(".mkv")
|| path.endsWith(".mov")
|| path.endsWith(".mp4")
|| path.endsWith(".mpg")
|| path.endsWith(".rm")
|| path.endsWith(".rmvb")
|| path.endsWith(".swf")
|| path.endsWith(".ts")
|| path.endsWith(".wmv")
|| path.endsWith(".m2v")) {
return TYPE_VIDEO;
} else if (path.endsWith(".m4a")
|| path.endsWith(".ac3")
|| path.endsWith(".amr")
|| path.endsWith(".au")
|| path.endsWith(".flac")
|| path.endsWith(".md")
|| path.endsWith(".mmf")
|| path.endsWith(".mp3")
|| path.endsWith(".ogg")
|| path.endsWith(".ra")
|| path.endsWith(".wav")
|| path.endsWith(".wma")
|| path.endsWith(".ape")
|| path.endsWith(".aac")
|| path.endsWith(".rm")
|| path.endsWith(".mp2")
|| path.endsWith(".m4r")) {
return TYPE_MUSIC;
} else if (path.endsWith(".bmp")
|| path.endsWith(".gif")
|| path.endsWith(".jpg")
|| path.endsWith(".pcx")
|| path.endsWith(".png")
|| path.endsWith(".tga")
|| path.endsWith(".tif")) {
return TYPE_IMG;
} else {
return TYPE_UNKNOW;
}
}
/**
* 打开文件
*
* @param path
*/
public void openFile(String path) {
//Uri uri = Uri.parse("file://"+file.getAbsolutePath());
Intent intent = new Intent();
//设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
//获取文件file的MIME类型
String type = getMIMEType(path);
if (type.equals("application/vnd.android.package-archive")) {
Log.d(TAG, "是否有权限进行安装" + mContext.getPackageManager().canRequestPackageInstalls());
if (!mContext.getPackageManager().canRequestPackageInstalls() && mContext instanceof FileManagerActivity) {
Log.d(TAG, " 当前没有安装权限,使用的是 FileManagerActivity Context");
FileManagerActivity mActivity = (FileManagerActivity) mContext;
mActivity.initPermissions();
return;
}
}
File file = new File(path);
//设置intent的data和Type属性。
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.d(TAG, " Version > Android.N");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// if(file.getAbsolutePath().startsWith(Environment.getExternalStorageDirectory().getAbsolutePath())){
// uri = FileProvider.getUriForFile(mContext, "packagename.fileprovider", file);//请使用自己的包名
// }else{
// uri = Uri.parse("content://" + file.getAbsolutePath());
// }
uri = FileProvider.getUriForFile(mContext, "com.vtech.projector.launcher.fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
} else {
Log.d(TAG, " Version < Android.N");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
uri = Uri.fromFile(file);
}
//跳转
intent.setDataAndType(uri, type);
try {
mContext.startActivity(intent);
}catch (Exception e){
e.printStackTrace();
Log.d(TAG," Vtech Activity Not Found");
}
}
public static void openFileByWps(Context context, File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setClassName("cn.wps.moffice", "cn.wps.moffice.documentmanager.PreStartActivity");
Uri uri = Uri.fromFile(file);
intent.setData(uri);
context.startActivity(intent);
}
public String getMIMEType(String path) {
String mimeType = "";
path = path.toLowerCase();
for (String[] mimetype : MIME_MapTable) {
if (path.endsWith(mimetype[0])) {
Log.d(TAG, "mimetype[0] " + mimetype[0] + " type is " + mimetype[1]);
mimeType = mimetype[1];
break;
}
}
Log.d(TAG, "ret " + mimeType);
return mimeType;
}
//建立一个MIME类型与文件后缀名的匹配表
private static final String[][] MIME_MapTable = {
//{后缀名, MIME类型}
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{".prop", "text/plain"},
{".rar", "application/x-rar-compressed"},
{".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"},
{".rtf", "application/rtf"},
{".sh", "text/plain"},
{".tar", "application/x-tar"},
{".tgz", "application/x-compressed"},
{".txt", "text/plain"},
{".wav", "audio/x-wav"},
{".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"},
//{".xml", "text/xml"},
{".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/zip"},
};
}
CommonConst.java
public class CommonConst {
public static final int FILE_TYPE_IMG = 1;
public static final int FILE_TYPE_DOC = 2;
public static final int FILE_TYPE_PPT = 3;
public static final int FILE_TYPE_VIDEO = 4;
public static final int FILE_TYPE_DIRECTORY = 5;
public static final int DEVICE_FIND_PORT = 9000;
public static final String READ_SERVICE_NOTI_CHANNEL_ID = "PROBE_SERVICE_NOTI_CHANNEL_ID";
public static final String READ_SERVICE_NOTI_CHANNEL_NAME = "PROBE_SERVICE_NOTI_CHANNEL_NAME";
public static final int READ_SERVICE_NOTI_ID = 1010;
}
FileIconBean.java
public class FileIconBean {
private boolean isDirectory;
private int file_type;
private String file_path;
private boolean isSelected;
private String file_name;
private String mime_type;
private boolean isUSBFile = false;
private long size;
public boolean isDirectory() {
return isDirectory;
}
public void setDirectory(boolean directory) {
isDirectory = directory;
}
public int getFile_type() {
return file_type;
}
public void setFile_type(int file_type) {
this.file_type = file_type;
}
public String getFile_path() {
return file_path;
}
public void setFile_path(String file_path) {
this.file_path = file_path;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public String getFile_name() {
return file_name;
}
public void setFile_name(String file_name) {
this.file_name = file_name;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getMime_type() {
return mime_type;
}
public void setMime_type(String mime_type) {
this.mime_type = mime_type;
}
public boolean isUSBFile() {
return isUSBFile;
}
public void setUSBFile(boolean USBFile) {
isUSBFile = USBFile;
}
@Override
public String toString() {
return "FileIconBean{" +
"isDirectory=" + isDirectory +
", file_type=" + file_type +
", file_path='" + file_path + '\'' +
", isSelected=" + isSelected +
", file_name='" + file_name + '\'' +
", mime_type='" + mime_type + '\'' +
", isUSBFile=" + isUSBFile +
", size=" + size +
'}';
}
}