我正在处理一个需要我获取所有文件名和文件夹(子文件夹)名称的项目。我试图通过在我的第一种方法中使用名为 yo 的 ArrayList 来做到这一点。
从头开始的代码如下:
public ArrayList varToList(File folder) {
for(File fileEntry : folder.listFiles()){
if(fileEntry.isDirectory()){
yo.add(fileEntry.getName());
varToList(fileEntry);
} else
yo.add(fileEntry.getName());
}
return yo;
}
从头开始执行代码后的输出:
[AddFilesDeflateComp.zip, AddFilesDeflateComp1.zip, AddFolder.zip, HAHAFolder, 200HAHA.txt, YO.txt, HAHAFolder.zip, RootText1.txt, RootText2.txt, RootText3.txt, test.zip, TestFolderA, TestFolderA1, text1.txt, Text2.txt, Text3.txt, TextA.txt, TextB.txt, TestFolderB, TestFolderC, TestFolder 4, boss.txt, New folder, play you.txt]
然后我改用另一种方法,因为上面显然无法做到。
这是获取文件结构的代码:
String folderName = "root";
ArrayList<String> folders = new ArrayList<String>();
ArrayList<String> files = new ArrayList<String>();
ArrayList<String> previousFiles = new ArrayList<String>();
Map<String, ArrayList> map2 = new LinkedHashMap<String, ArrayList>();
Map<String, ArrayList> map = new LinkedHashMap<String, ArrayList>();
public void listFilesForFolder(File folder) {
ArrayList<String> no = new ArrayList<String>();
files = new ArrayList<String>();
for (File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
previousFiles = files;
map2.put(folderName, previousFiles);
folders.add(folderName);
folderName = fileEntry.getName();
listFilesForFolder(fileEntry);
if (folders.size() - 1 != -1) {
folderName = folders.get(folders.size() - 1);
folders.remove(folders.get(folders.size() - 1));
files = map2.get(folderName);
}
} else {
files.add(fileEntry.getName());
map.put(folderName, files);
}
}
}
地图最终内容如下:
{root=[AddFilesDeflateComp.zip, AddFilesDeflateComp1.zip, AddFolder.zip, HAHAFolder.zip, RootText1.txt, RootText2.txt, RootText3.txt, test.zip], HAHAFolder=[200HAHA.txt, YO.txt], TestFolderA1=[text1.txt, Text2.txt, Text3.txt], TestFolderA=[TextA.txt, TextB.txt], TestFolder 4=[boss.txt, play you.txt]}
我的预期输出:
{root=[AddFilesDeflateComp.zip, AddFilesDeflateComp1.zip, AddFolder.zip, HAHAFolder.zip, RootText1.txt, RootText2.txt, RootText3.txt, test.zip],HAHAFolder=[200HAHA.txt, YO.txt],TestFolderA=[TextA.txt,TextB.txt,TestFolderA1=[text1.txt,Text2.txt,Text3.txt],TestFolderB=[TestFolderC=[TestFolder 4=[New folder,boss.txt,play you.txt]]]]}
上面的代码可以获取子文件夹的内容,并且可以获取文件夹的名称,但不能获取空的子文件夹或文件夹
执行上述代码时的文件结构:
根/ 哈哈文件夹 /200哈哈.txt /哟.txt 测试文件夹A /TestFolderA1 /text1.txt /Text2.txt /Text3.txt /TextA.txt /TextB.txt 测试文件夹B /TestFolderC /测试文件夹 4 /新建文件夹 /老板.txt /玩你.txt AddFilesDeflateComp.zip AddFilesDeflateComp1.zip 添加文件夹.zip 哈哈文件夹.zip RootText1.txt RootText2.txt RootText3.txt 测试.zip
有没有其他方法或如何修改上述代码以获得我需要的