我有一个ArrayList<String>
包含目录路径,例如:
/home, /usr...
我想编写一个代码,如果列表已包含该元素的父目录,则该代码将从列表中删除所有路径。 例如: 如果列表包含:
/home
/home/games
然后,/home/games 应该被删除,因为它的父级/home 已经在列表中。 下面是代码:
for (int i = 0; i < checkedList.size(); i++) {
File f = new File(checkedList.get(i));
if(checkedList.contains(f.getParent()));
checkedList.remove(checkedList.get(i));
}
以上checkedList
是 String arrayList
.
当列表包含以下内容时就会出现问题:
/home
/home/games/minesweeper
现在扫雷文件夹不会被删除,因为它的父游戏不在列表中。如何删除这些类型的元素?
最佳答案
另一种可能的解决方案是使用String.startsWith(String)
。
但是,您当然可以利用 File
类的父功能来处理相对目录和其他特殊性。遵循解决方案草案:
List<String> listOfDirectories = new ArrayList<String>();
listOfDirectories.add("/home/user/tmp/test");
listOfDirectories.add("/home/user");
listOfDirectories.add("/tmp");
listOfDirectories.add("/etc/test");
listOfDirectories.add("/etc/another");
List<String> result = new ArrayList<String>();
for (int i = 0; i < listOfDirectories.size(); i++) {
File current = new File(listOfDirectories.get(i));
File parent = current;
while ((parent = parent.getParentFile()) != null) {
if (listOfDirectories.contains(parent.getAbsolutePath())) {
current = parent;
}
}
String absolutePath = current.getAbsolutePath();
if (!result.contains(absolutePath)) {
result.add(absolutePath);
}
}
System.out.println(result);
这将打印:
[/home/user, /tmp, /etc/test, /etc/another]
关于java - 在ArrayList中,如果子目录的父目录已存在于列表中,如何删除子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11460417/