用java编写一个递归函数,获取指定目录下的所有文件夹名称
时间: 2024-02-01 18:02:01 浏览: 37
好的,以下是用 Java 编写的递归函数,可以获取指定目录下的所有文件夹名称:
```java
import java.io.File;
public class FolderNames {
public static void main(String[] args) {
String path = "your/directory/path";
File folder = new File(path);
if (folder.exists()) {
String[] folderNames = getFolderNames(folder);
System.out.println("Folder names in " + path + ":");
for (String folderName : folderNames) {
System.out.println(folderName);
}
} else {
System.out.println("Directory not found.");
}
}
public static String[] getFolderNames(File folder) {
String[] folderNames = folder.list((dir, name) -> new File(dir, name).isDirectory());
for (int i = 0; i < folderNames.length; i++) {
folderNames[i] = folder.getAbsolutePath() + "/" + folderNames[i];
}
for (String subFolder : folderNames) {
File subFolderFile = new File(subFolder);
String[] subFolderNames = getFolderNames(subFolderFile);
if (subFolderNames.length > 0) {
folderNames = concatStringArrays(folderNames, subFolderNames);
}
}
return folderNames;
}
public static String[] concatStringArrays(String[] arr1, String[] arr2) {
String[] result = new String[arr1.length + arr2.length];
System.arraycopy(arr1, 0, result, 0, arr1.length);
System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
return result;
}
}
```
你可以将 `your/directory/path` 替换为你想要获取文件夹名称的目录路径。这个函数会返回一个字符串数组,包含指定目录下所有文件夹的名称。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)