0

I'm really new to programming so please be patient with me. I've searched the net and couldn't find a post specific to what I need done. I need to take a text list of file names (I do not have the extension of the file, it should be .sgm .xml.pdf) and search a directory and all its sub-directories for a file name match. If the match is found it should output the directory location then move on to the next file name.

The code below doesn't search the subdirectory.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

 
/**
 * Class takes a text file and searches a directory for matching file names and outputs a new file with the paths of found directories.
 * 
 * @author Rishal
 *
 */
public class CheckFileNames {
    public static void main(String[] args) throws IOException {
 

        // Path of the file which is having all the names of the files
        String list = "C:\\Test\\AF IPT Search\\Test_FileNames.txt";
        List listOfFileNamesToCheck = Files.readAllLines(Paths.get(list), Charset.forName("UTF-8"));
 
        // Input object to get input from the user
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
        // Reading source and destination from the user
        System.out.println("Enter Source folder path:");
        String sourceFolder = br.readLine();
 
 
        // getting list of all the files present in the source folder
        File[] fList = directory.listFiles();
 
        // Looping into each fileNames present in the listOfFiles.txt to check
        // if its present in the source folder
        for (String loopInFileNames : listOfFileNamesToCheck) {
            for (File file : fList) { // looping into the Source Folder
                                        // fileNames
 
                // Matching the fileNames in the sourceFolder and list of files
                // supplied by the user.
                if (file.isFile() && file.getName().equals(loopInFileNames)) {
                    // Copying the file into the target folder.
                    System.out.println(file.getName())).toPath());
                }
            }
            //System.out.println(loopInFileNames + " :Files Copied Succesfully!");
        }
    }
}```
JenPann
  • 41
  • 7
  • in the for loop you are handling the case for files (if file.isFile() ..) part, you should add another condition for the case when it isn't a file and is a directory – Janar Feb 25 '22 at 20:58
  • I'm sorry I don't understand what you're saying. – JenPann Feb 25 '22 at 21:04
  • He means you need to go into the directory in your `for` if your `if` is false and the current object is a directory. – Alias Cartellano Feb 25 '22 at 21:19

0 Answers0