gpt4 book ai didi

java - foreach循环错误

转载 作者:行者123 更新时间:2023-12-01 07:31:06 25 4
gpt4 key购买 nike

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());

}

}

最佳答案

移动此行

PictureFile picturefile = new PictureFile();

在循环内,否则您只更新一个元素。

关于java - foreach循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17515131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com