Java For-each-loop:我正在尝试将从下面的操作中检索到的数据映射并将其映射到对象模型。不幸的是,它只输出检索到的对象的最后一个对象。请任何人都可以检查代码可能有什么问题。
public void listAllFilesInTheDirectoryAndSubdirectories(String aDirectoryName){
AppDirectory appdirectory = new AppDirectory();
PictureFile picturefile = new PictureFile();
ArrayList<AppDirectory> subdirectories = new ArrayList<AppDirectory>();
ArrayList<PictureFile> picturefiles = new ArrayList<PictureFile>();
appdirectory.setName(aDirectoryName);
appdirectory.setPictureFiles(picturefiles);
appdirectory.setSubDirectories(subdirectories);
File directory = new File(aDirectoryName);
//get all the files from a directory
File[] allFiles = directory.listFiles();
//Using a for-each loop to loop through each file in the list of files returned
for (File file : allFiles){
//Check if the file is-a-file, then print it out
if (file.isFile()){
String filePath = file.getAbsolutePath();
String fileName = file.getName();
String folderName = file.getParentFile().getName();
if(folderName.equals(aDirectoryName)){
System.out.println("Directory Name is : "+appdirectory.getName());
System.out.println(folderName);
System.out.println(fileName);
picturefile.setName(fileName);
picturefile.setType("jpeg");
picturefile.setLength(2354);
Dimension dimension = new Dimension(656, 413);
picturefile.setSize(dimension);
picturefile.setLength(50023);
appdirectory.addPictureFile(picturefile);
}else{
//appdirectory.setName(folderName);
//picturefile.setName(filePath);
//appdirectory.addPictureFile(picturefile);
//subdirectories.add(appdirectory);
}
}else if(file.isDirectory()){
listAllFilesInTheDirectoryAndSubdirectories(file.getAbsolutePath());
}
}
// System.out.println(picturefiles.size());
for(int x = 0; x<appdirectory.getPictureFiles().size(); x++){
System.out.println(appdirectory.getPictureFiles().get(x).getName());
}
}