/** * Add a mapping from a name to a filesystem root. The provider only offers * access to files that live under configured roots. */ //读取xml配置文件,建立名称和目录的映射表 voidaddRoot(String name, File root){ //名字不能为空 if (TextUtils.isEmpty(name)) { thrownew IllegalArgumentException("Name must not be empty"); }
try { // Resolve to canonical path to keep path checking fast root = root.getCanonicalFile(); } catch (IOException e) { thrownew IllegalArgumentException( "Failed to resolve canonical path for " + root, e); }
mRoots.put(name, root); }
@Override public Uri getUriForFile(File file){ String path; try { //获取路径 path = file.getCanonicalPath(); } catch (IOException e) { thrownew IllegalArgumentException("Failed to resolve canonical path for " + file); }
// Find the most-specific root path Map.Entry<String, File> mostSpecific = null; //遍历查找文件路径对应的名称 for (Map.Entry<String, File> root : mRoots.entrySet()) { final String rootPath = root.getValue().getPath(); if (path.startsWith(rootPath) && (mostSpecific == null || rootPath.length() > mostSpecific.getValue().getPath().length())) { mostSpecific = root; } }
//查询未果,说明在xml中未定义 if (mostSpecific == null) { thrownew IllegalArgumentException( "Failed to find configured root that contains " + path); }
// Start at first char of path under root final String rootPath = mostSpecific.getValue().getPath(); if (rootPath.endsWith("/")) { path = path.substring(rootPath.length()); } else { path = path.substring(rootPath.length() + 1); }
// Encode the tag and path separately path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/"); //构建content Uri,这就是最后我们拿到的内容 returnnew Uri.Builder().scheme("content") .authority(mAuthority).encodedPath(path).build(); }
@Override public File getFileForUri(Uri uri){ String path = uri.getEncodedPath();
//通过uri反向寻找,和上面的原理差不多,不赘述 finalint splitIndex = path.indexOf('/', 1); final String tag = Uri.decode(path.substring(1, splitIndex)); path = Uri.decode(path.substring(splitIndex + 1));
final File root = mRoots.get(tag); if (root == null) { thrownew IllegalArgumentException("Unable to find configured root for " + uri); }
File file = new File(root, path); try { file = file.getCanonicalFile(); } catch (IOException e) { thrownew IllegalArgumentException("Failed to resolve canonical path for " + file); }