我正在尝试搜索图像文件夹以检查文件夹中的每个图像路径是否包含来自我的 ArrayList 的字符串元素。如果文件路径包含字符串元素,我想将其添加到新的字符串数组中。这是我到目前为止。与数组列表中的字符串匹配的图像路径在 for 循环中正确打印,但在循环之外它打印 null。
/*ArrayList content:
Snow Fall.jpg
Soft snow.jpg
Winter Wonderland.jpg
*/
public void getImages(ArrayList<String> theImagesArrayList) {
File dir = new File("C:/Users/someone/Desktop/slideshow images");
int count=0;
File[] files = dir.listFiles();
file = new String[theImagesArrayList.size()];
for (int i = 0; i < theImagesArrayList.size(); i++) {
for (File b : files) {
if (theImagesArrayList.contains(b.getName())) {
count++;
if(count<=theImagesArrayList.size()){
file[i] = b.getPath();
System.out.println(file[i]);
/*Output from above print statement:
C:\Users\someone\Desktop\slideshow images\Snow Fall.jpg
C:\Users\someone\Desktop\slideshow images\Soft snow.jpg
C:\Users\someone\Desktop\slideshow images\Winter Wonderland.jpg
*/
}
}
}
}
System.out.println(" ");
for(String c: file){
System.out.println(c);
}
/*Output above loop:
C:\Users\someone\Desktop\slideshow images\Winter Wonderland.jpg
null
null
*/
}
}
}
}
这count++
就是问题所在。file[i] = b.getPath();
在第一次外部迭代中执行所有 3 次,在接下来的迭代中不再执行。所以,所有三个路径都写在file[0]
. 这就是为什么file[1]
和file[2]
保持为空。
尝试break;
按照System.out.println(file[i]);
说明操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句