【问题标题】:How to check if elements in a file names in a folder contain string names in an arraylist of strings?如何检查文件夹中文件名中的元素是否包含字符串数组列表中的字符串名称?
【发布时间】:2018-11-17 04:35:45
【问题描述】:

我正在尝试搜索图像文件夹以检查每个图像是否 文件夹中的路径包含来自我的 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
     */
    }
  }
 }
}

【问题讨论】:

    标签: java arrays arraylist directory


    【解决方案1】:

    count++ 是问题所在。 file[i] = b.getPath(); 在第一次外部迭代中全部执行了 3 次,在接下来的迭代中不再执行。因此,所有三个路径都写在file[0] 中。这就是file[1]file[2] 保持为空的原因。

    System.out.println(file[i]); 指令之后尝试break;

    【讨论】:

      【解决方案2】:

      内部循环中变量“i”的值在第一次迭代中始终为0,因此赋值后“i”的值不会递增,因此总是被最新的值覆盖。

      代替语句:file[i] = b.getPath();

      您可以使用如下语句:file[j++] = b.getPath(); // 贴花并在之前初始化 j=0。

      【讨论】:

        猜你喜欢
        • 2010-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 2014-12-23
        • 1970-01-01
        • 2013-10-03
        • 1970-01-01
        相关资源
        最近更新 更多