gpt4 book ai didi

java - 获取字符串路径的公共(public)根和该路径的文件夹列表

转载 作者:太空狗 更新时间:2023-10-29 16:22:36 37 4
gpt4 key购买 nike

我有 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

我想做的是找到这些路径的公共(public)根并获取该公共(public)根的一级文件夹(唯一)列表。

例如

第一次运行:parent root = null(这是第一次运行)公共(public)根 ->/mnt/sdcard/文件夹列表- 文件夹 1- 文件夹 2

第二次运行(现在父根将是/mnt/sdcard/folder1/)公共(public)根 ->/mnt/sdcard/folder1/(与父根相同)文件夹列表- 一种-e

第二次运行(现在父根将是/mnt/sdcard/folder1/a/)公共(public)根 ->/mnt/sdcard/folder1/a/b(与父根相同)文件夹列表 -> 空(我会得到文件)

有没有办法通过 db 来执行这些过滤器,或者我必须通过代码来执行?

提出这个问题是因为我需要提供一个 Android 音乐库的文件夹 View ,用于存储歌曲数据库记录中的路径。

最佳答案

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

关于java - 获取字符串路径的公共(public)根和该路径的文件夹列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10911219/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com