Skip to content
Advertisement

Compare the String array elements with the file names in a folder if matches move them to another folder

I have this requirement where I have some files.
Say – file1.txt file2.txt in a folder –> Files ->> C:/Files
Inside this folder I have two other folders
Completed ->> C:/Files/Completed and Error C:/Files/Error

Now I have this String array : String arr[]={file1, file2};
I need to compare the string arry elements with the file names in the folder Files.
If any of the name matches then those original files will be moved to the Completed folder otherwise to the Error folder.

Here’s what I was trying to do but couldn’t get through it

String arr[]={file1, file2};
List<String> textFiles = new ArrayList<File>();
List<String> directories = new ArrayList<File>();

File[] files = new File("C:/Files").listFiles();
for (File file : files) { 
            if(file.isFile()){ 
                textFiles.add(file.getName());
            }else
                directories.add(file.getName());
        }

 for(int i = 0; i < textFiles.size(); i++){
            if(textFiles.equals(sampleids)){
                logger.info(textFiles.get(i));
                //FileOutputStream fStream = new FileOutputStream();
   }
}

Advertisement

Answer

Based on the title of your post, the code below will do the task required however do keep in mind that the file names you have supplied within your String Array do not have file name extensions. I’m not sure if this is a requirement or just an over-site. In any case the code takes this into account and will distinguish between names with or without extensions.

If the ‘Completed’ folder and or the ‘Error’ folder do not exist within the ‘Files’ folder then they are automatically created.

Access Permissions within the local file system will be your responsibility to establish and ensure they exist.

Read the comments in code:

    String completedArray[] = {"file1", "file2"};
    List<String> completedFiles = new ArrayList<>();    // Files moved to the 'Completed' folder.
    List<String> notCompletedFiles = new ArrayList<>(); // Files moved to the 'Error' folder.

    File[] files = new File("C:/Files").listFiles();
    // Does the 'Completed' folder exist? If not, create it.
    File checkPath = new File("C:/Files/Completed");
    if (!checkPath.exists()) {
        checkPath.mkdirs();
    }
    // Does the 'Error' folder exist? If not, create it.
    checkPath = new File("C:/Files/Error");
    if (!checkPath.exists()) {
        checkPath.mkdirs();
    }

    /* Check Files within the 'Files' folder against 
       the file names within the 'completed' array...
       Note that the file names contained within the
       completedArray string array DO NOT contain file
       name extensions. This is how the OP portrays this
       within his/her code.
    */
    
    // Iterate through the files within the 'Files' folder...
    for (File file : files) {
        // Is this an actual file?
        if (file.isFile()) {
            // Yes...
            // Get file name WITH file name extension
            String fileName = file.getName();
            // Get the file name WITHOUT the file name extension (ie: no .txt)
            String fileName_NoExtension = file.getName().substring(0, file.getName().lastIndexOf("."));
            
            boolean fileMoved = false; // Flag to indicate file was successfully moved.
            // Check to see if the file name is contained within our list 
            // (array) of completed files?
            for (String completed : completedArray) {
                String name;
                // Add extensions as you see fit.
                if (completed.matches("([^\s]+(\.(?i)(txt|csv|doc|pdf))$)")) {
                    name = fileName;
                }
                else {
                    name = fileName_NoExtension;
                }
                // Is there a match?
                if (completed.equalsIgnoreCase(name)) {
                    // Yes...
                    //Move the file to 'Completed' folder
                    try {
                        java.nio.file.Path temp = Files.move(Paths.get(file.getAbsolutePath()),
                                Paths.get("C:/Files/Completed/" + file.getName()));

                        if (temp != null) {
                            // Add the completed, moved file to the 'completedFiles' collection.
                            completedFiles.add(file.getAbsolutePath());
                            fileMoved = true; // Indicated move was successfull.
                        }
                        else {
                            // Indicate there was a problem. Moving the file failed.
                            System.err.println("Failed to move the file");
                        }
                    }
                    catch (IOException ex) {
                        // Display the exception if one occurres.
                        System.err.println("FAILED TO MOVE FILE...");
                        System.err.println(ex.getMessage());
                    }
                }
            }
            /* If the fileMoved flag is still false then there was 
               either an error in moving the file OR the file was
               not indicated within our 'completedFiles' array, so, 
               move the file to the 'Error' folder.            */
            if (!fileMoved) {
                try {
                    java.nio.file.Path temp = Files.move(Paths.get(file.getAbsolutePath()),
                            Paths.get("C:/Files/Error/" + file.getName()));

                    if (temp != null) {
                        // Add the moved file to the 'notCompletedFiles' collection.
                        notCompletedFiles.add(file.getAbsolutePath());
                        fileMoved = true;
                    }
                    else {
                        // Indicate there was a problem. Moving the file failed.
                        System.err.println("Failed to move the file");
                    }
                }
                catch (IOException ex) {
                    // Display the exception if one occurres.
                    System.err.println("FAILED TO MOVE FILE...");
                    System.err.println(ex.getMessage());
                }
            }
        }
    }
    
    // Display Completed files moved to the 'Completed' folder...
    System.out.println();
    System.out.println("Files moved to the 'Completed' folder (C:\Files\Completed):");
    System.out.println("===========================================================");
    for (String comp : completedFiles) {
        System.out.println(comp);
    }
    
    // Display Non-Completed files moved to the 'Error' folder...
    System.out.println();
    System.out.println("Files moved to the 'Error' folder (C:\Files\Error):");
    System.out.println("===================================================");
    for (String nonComp : notCompletedFiles) {
        System.out.println(nonComp);
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement