java 我必须从Directory中筛选与我添加的ArrayList中的相同文件扩展名匹配的文件

nlejzf6q  于 2022-12-17  发布在  Java
关注(0)|答案(1)|浏览(146)
String folderpath = "G:\\AE_IntegrationComp";
        //Above is Folder where is Different files are present
        
        List <String>filet = new ArrayList<String>();
        filet.add(".txt");
        filet.add(".doc");
        //extension which I added
        
        for(String str : filet)
        {
            
        }
        File directory = new File(folderpath);
        for(File list : directory.listFiles())
        {
            if(list.getName().contains(""))
            {
                System.out.println(list.getName());
            }
        }

我必须检查目录是否为空,如果不是,数组列表中的文件扩展名应与扩展名匹配目录中是否可用,并打印匹配的文件

kcrjzv8t

kcrjzv8t1#

你要做的是:
1.遍历目录中的所有文件(您已经完成了)
1.检查它是否有一定的扩展名(它以一定的字符串结尾)
1.如果匹配,则打印文件名。

public class Main {

  // Here we have a constant containing the interesting file extensions
  public static final String[] extensions = new[] { ".txt", ".doc" };

  // This helper function will tell us whether 
  // a file has one of the interesting file extensions
  public static boolean matchesExtension(File file) {
    for(String ext : extensions) {
      if(file.getName().endsWith(ext)) { 
         return true; 
      }
    }
    return false;
  }

  public static void main(String[] args) {
        String folderpath = "G:\\AE_IntegrationComp";
        File directory = new File(folderpath);
        // Iterate through all files in the directory
        for(File file : directory.listFiles()){
            if(matchesExtension(file)){
                System.out.println(file.getName());
            }
        }

  }
}

相关问题