Search code examples
javaarraylistreadfile

how to Ignore certain files from main folder when reading .txt file using arraylist


i have a main folder(config) and a text file called ignore.txt. i have mentioned few files to ignore from main folder in ignore.txt file. i need some help how do i call ignore.txt file to execute and ignore files from the main folder(config).

public class filetext {
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("/path to /Configs");
        ArrayList<File> fileList = new ArrayList<File>(Arrays.asList(file.listFiles()));
        
        System.out.println(fileList);
        
        File ignorefile = new File("/path to /ignore.txt");
        Scanner sc = new Scanner(ignorefile); 
        ArrayList<List> ignorelist = new ArrayList<List>();

        System.out.println(ignorefile);
        
        if(ignorelist.contains(file)); 
        fileList.remove(file);
        System.out.println(ignorelist);
        }

Solution

  • As far as I am understanding, you want to remove the "ignored files" from your files list.

    To remove the loaded "ignored names" from your fileList, you can edit your code to something like this although it is not an efficient approach:

    public static void main(String[] args) throws FileNotFoundException {
            File file = new File("path of my main folder");
            ArrayList<File> fileList = new ArrayList<File(Arrays.asList(file.listFiles()));
            
            File ignoreFile = new File("path to /ignore.txt");
            Scanner sc = new Scanner(ignorefile); 
            ArrayList<String> listOfLines = new ArrayList<>();
            while (sc.hasNextLine()) 
                listOfLines.add(scanner.nextLine());
            
            for(File f : fileList){
               if(listOfLines.contains(f.getFileName())
                  fileList.remove(f);
            }
    
            // print the fileList again
          }