我在获取表格中的文件列表时遇到了一些问题。这是我的listFilesForFolder
方法:
class listFilesForFolder{
public void listFilesForFolder(final File folder) {
String[ ] table = new String[5] ;
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
table[0] = fileEntry.getPath();
} else {
System.out.println(fileEntry.getPath());
System.out.println(table[0]);
}
}
}
给我:
/home/piotr/Pobrane/162372-1.jpg
null
/home/piotr/Pobrane/skype-4.3.0.37-suse.i586.rpm
null
如何用文件路径填充表格?
答案 0 :(得分:1)
简单
fileEntry.isDirectory()
正在返回false
,因此它永远不会满足
if (fileEntry.isDirectory())
因此未设置table[0]
值。
删除整个if-else
块并将其替换为
table[0] = fileEntry.getPath(); // or whatever method you want to use to increment i
int i = 0;
for (final File fileEntry : folder.listFiles()) {
table[i++] = fileEntry.getPath();
}
答案 1 :(得分:1)
我认为你需要一个列表,而不是一个数组。如果不以递归方式调用该方法,则会丢失子文件夹的所有文件。如果要获取子文件夹的文件,请使用以下内容:
public List<String> listFilesForFolder(final File folder) {
List<String> list = new ArrayList<>();
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
list.addAll(listFilesForFolder(fileEntry)); //recursively call the same method to get the files of the subfolder
} else {
list.add(fileEntry.getPath()); //add the files of this folder to the list
System.out.println(fileEntry.getPath()); //prints only the files of all subfolders
}
}
return list; //returns all the files of this folder and all the files of its subfolders
}
如果您要求最终输出是数组而不是列表,那么只需将此列表转换为数组,在您调用listFilesForFolder
的方法中,就像这样:
List<String> list = listFilesForFolder(intialFile);
String[] table = new String[list.size()];
table = list.toArray(table); //the result as an array