我写了一段代码,将所有CSV文件的内容附加到列表中。编译该程序会在'''Iterator iter = full_files.iterator();'''
行中生成“找不到符号”错误。我检查了声明,一切似乎都很好。我已经在上一行中声明并初始化了full_files。
public ArrayList<String[]> readCSV(File FDir) throws IOException {
File[] files = FDir.listFiles();
File F = files[0];
ArrayList<String[]> all_list = new ArrayList<>();
ArrayList<String[]> list = new ArrayList<>();
// Creating a file to point to the "Full" directory
File FullDir = new File(F.getParent() + "/Full/");
File[] full_files = FullDir.listFiles();
Iterator<File> iter = full_files.iterator();
// Iterating through the files in "Full"
while(iter.hasNext()) {
File file = iter.next();
if(GetFileExtension.get(file).equals(".csv")) {
list = CSVHandler.readCSV(file);
all_list.addAll(list);
}
}
// Checking if the file outside "Full" is a CSV
if(GetFileExtension.get(F).equals(".csv")) {
list = CSVHandler.readCSV(F);
all_list.addAll(list);
}
return all_list;
}
这是我在编译过程中遇到的错误。
shared/utilities/main.java:82: error: cannot find symbol
Iterator<File> iter = full_files.iterator();
^
symbol: method iterator()
location: variable fast of type File[]
1 error
答案 0 :(得分:0)
首先,由于Java 7以来的for(File file : full_files)
,您甚至不需要Iterator。
这是一个有效的版本:
public List<String[]> readCSV(File dir) throws IOException {
File[] files = dir.listFiles();
List<String[]> allMatchingFiles = new ArrayList<>();
if (files == null || files.length < 1) {
return allMatchingFiles;
}
File firstFile = files[0];
// Creating a file to point to the "Full" directory
File fullDir = new File(firstFile.getParent() + "/Full/");
File[] fullDirFiles = fullDir.listFiles();
// Iterating through the files in "Full"
if (fullDirFiles != null) {
for (File file : fullDirFiles) {
if (GetFileExtension.get(file).equals(".csv")) {
allMatchingFiles.addAll(CSVHandler.readCSV(file));
}
}
}
// Checking if the file outside "Full" is a CSV
if (GetFileExtension.get(firstFile).equals(".csv")) {
allMatchingFiles.addAll(CSVHandler.readCSV(firstFile));
}
return allMatchingFiles;
}
您可能会看到,我在防御性上写得更清楚,例如检查null。 我也用List <>代替了ArrayList <>。
此外,在Java中,通常使用lowerCamelCase作为变量名。
@Joakim Danielson:好的,请相应地更改代码:)