我有SQLite3数据库表,其中存储了这样的路径列表:
/mnt/sdcard/folder1/a/b/file1
/mnt/sdcard/folder1/a/b/file2
/mnt/sdcard/folder1/a/b/file3
/mnt/sdcard/folder1/a/b/file4
/mnt/sdcard/folder1/a/b/file5
/mnt/sdcard/folder1/e/c/file6
/mnt/sdcard/folder2/d/file7
/mnt/sdcard/folder2/d/file8
/mnt/sdcard/file9
我要做的是找到这些路径的公共根目录,并获取该公共根目录的第一级文件夹(唯一)列表。
例如
第一次运行:父级root = null(这是第一次运行)
通用根目录-> / mnt / sdcard /
资料夹清单
-folder1
-folder2
第二次运行(现在父根目录为/ mnt / sdcard / folder1 /)
通用根目录-> / mnt / sdcard / folder1 /(与父根目录相同)
资料夹清单
- 一个
-e
第二次运行(现在父根目录为/ mnt / sdcard / folder1 / a /)
公用根-> / mnt / sdcard / folder1 / a / b(与父根相同)
文件夹列表->空(我将获取文件)
有没有一种方法可以通过db进行这些过滤,或者我可以通过代码来进行过滤?
提出这个问题是因为我需要提供Android音乐库的文件夹视图,该文件夹视图将路径存储在歌曲db记录中。
最佳答案
看看http://rosettacode.org/wiki/Find_common_directory_path
它以某些编程语言实现。
这是我测试并用于我的目的的Java示例。
public class CommonPath {
public static String commonPath(String... paths){
String commonPath = "";
String[][] folders = new String[paths.length][];
for(int i = 0; i < paths.length; i++){
folders[i] = paths[i].split("/"); //split on file separator
}
for(int j = 0; j < folders[0].length; j++){
String thisFolder = folders[0][j]; //grab the next folder name in the first path
boolean allMatched = true; //assume all have matched in case there are no more paths
for(int i = 1; i < folders.length && allMatched; i++){ //look at the other paths
if(folders[i].length < j){ //if there is no folder here
allMatched = false; //no match
break; //stop looking because we've gone as far as we can
}
//otherwise
allMatched &= folders[i][j].equals(thisFolder); //check if it matched
}
if(allMatched){ //if they all matched this folder name
commonPath += thisFolder + "/"; //add it to the answer
}else{//otherwise
break;//stop looking
}
}
return commonPath;
}
public static void main(String[] args){
String[] paths = { "/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths));
String[] paths2 = { "/hame/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths2));
}
}