gpt4 book ai didi

java - 在java中从文件夹ID和父ID创建文件夹

转载 作者:搜寻专家 更新时间:2023-10-30 22:18:41 24 4
gpt4 key购买 nike

我需要创建一个类来获取存储在数据库中的文件夹列表,并在本地计算机上以正确的层次结构创建它们。

文件夹在数据库中的排列方式如下:

id name parent_id1 documents 02 movies 03 videos 04 my files 15 desktop 06 other 4

So documents, movies, videos and desktop are in the root. 'my files' goes in the folder with the id of 1(documents) and 'other' goes in the folder with the id of 4(my files)

I have been trying to do it by using a whyle loop but dont know how to get them to go into the correct folders.

try {
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
while( i < 50 )
{
try {

Statement st = con.createStatement();
ResultSet result = st.executeQuery("SELECT name, id, parent_id FROM categories WHERE parent_id = '"+PID+"' AND repository_id = '"+RepoID+"'");



while (result.next ())
{
String FolderName = result.getString ("name");
String FolderId = result.getString ("id");
String FolderId = result.getString ("parent_id");
make the folder name here
System.out.println( FolderName+" "+FolderId );
}

System.out.println( " ");
i++ ;
PID++;
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}

最佳答案

创建一个文件夹对象来存储数据,然后在您从数据库中读取数据时构建这些对象。构建完所有 Folder 对象后,执行最后一个循环以将每个 Folder 绑定(bind)到其父类。也许是这样的:

class Folder {
private String name;
private int id;
private int parentId;
private List<Folder> children = new ArrayList<Folder>();

public Folder(String name, int id, int parentId) {
this.name = name;
this.id = id;
this.parentId = parentId;
}

public void addChildFolder(Folder folder) {
this.children.add(folder);
}

public List<Folder> getChildren() {
return Collections.unmodifiableList(children);
}

public int getParentFolderId() {
parentId;
}

public String getName() {
return name;
}

public int getId() {
return id;
}
}

现在当您从数据库中读取数据时,您创建了这些 Folder 对象(没有子对象)并将它们添加到 map 中:

Map<Integer, Folder> data = new HashMap<Integer, Folder>();

... loop through your result set getting folder data...
Folder newFolder = new Folder(nameString, id, parentId);
data.put(newFolder.getId(), newFolder);

使用 Integer.valueOf(String) 将 String 转换为 int。

一旦创建了所有文件夹,就可以进行最后一个循环,将父文件夹连接到子文件夹,如下所示:

for(Folder folder : data.values()) {
int parentId = folder.getParentFolderId();
Folder parentFolder = data.get(parentId);
if(parentFolder != null)
parentFolder.addChildFolder(folder);
}

最后,只需获取 ID 为 0 的文件夹并开始在磁盘上构建文件,使用 folder.getChildren() 作为向下移动树的便捷方式。查看 File 对象上的 javadoc,您会特别想使用 mkdirs() 方法。

希望对您有所帮助。

关于java - 在java中从文件夹ID和父ID创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7532130/

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