model如下,功能一目了然:
public class FileInfo {
// id value in DB
public long id;
// true if file is a directory
public boolean isDir;
// true if file is hidden
public boolean isHidden;
// full name of the file
public String fileName;
// the path which the file in
public String filePath;
// file size in bytes
public long fileSize;
// last modified timestamp
public long modifiedTimeMillis;
// icon (adoptable)
public Drawable icon;
public boolean hasThumb;
//if isDir is true, get file count in this dir
public int fileCount;
//resolution of pictures
public int height = 0;
public int width = 0;
public static FileInfo createInfo(File file, final boolean includeHidden) {
FileInfo info = new FileInfo();
if (file == null) {
return info;
}
try {
info.filePath = file.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
info.filePath = file.getAbsolutePath();
}
info.fileName = file.getName();
info.fileSize = file.length();
info.modifiedTimeMillis = file.lastModified();
info.isDir = file.isDirectory();
info.isHidden = file.isHidden();
info.fileCount = 0;
if (info.isDir) {
File[] list = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (!includeHidden && filename.startsWith(".")) {
return false;
}
return true;
}
});
if (list != null) {
info.fileCount = list.length;
}
} else {
info.hasThumb = ThumbUtils.getThumbnailType(file) != null;
}
return info;
}
}
获取内外置存储卡,OTG路径的方法(使用反射):
private List<FileInfo> goGetStorages() {
List<FileInfo> list = new ArrayList<>();
StorageManager sm = (StorageManager) mApplication.getSystemService(Context.STORAGE_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Class<?> klass = StorageVolume.class;
try {
Method method = klass.getMethod("getPathFile");
List<StorageVolume> volumes = sm.getStorageVolumes();
for (StorageVolume volume : volumes) {
FileInfo info = FileInfo.createInfo((File) method.invoke(volume), true);
info.fileName = volume.getDescription(mApplication);
list.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
Class<?> klass = StorageManager.class;
Method method = klass.getMethod("getVolumePaths");
String[] paths = (String[]) method.invoke(sm);
if (paths != null) {
for (String path : paths) {
list.add(FileInfo.createInfo(new File(path), true));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}