Slip No 5 Q B

Q. Write a java program to accept list of file names through command line. Delete the files having extension .txt. Display name, location and size of remaining files. [25 M]

import java.io.File;

public class FileOperations {
    public static void main(String[] args) {

        // Check if command line arguments are provided
        if (args.length == 0) {
            System.out.println("No file names provided through command line.");
            return;
        }

        // Process each file name
        for (int i = 0; i < args.length; i++) {

            File file = new File(args[i]);

            // Check file existence
            if (!file.exists()) {
                System.out.println("File not found: " + args[i]);
                continue;
            }

            // Delete .txt files
            if (args[i].toLowerCase().endsWith(".txt")) {
                if (file.delete()) {
                    System.out.println("Deleted file: " + args[i]);
                } else {
                    System.out.println("Unable to delete file: " + args[i]);
                }
            }
            else {
                // Display remaining file details
                System.out.println("\nRemaining File Details:");
                System.out.println("Name     : " + file.getName());
                System.out.println("Location : " + file.getAbsolutePath());
                System.out.println("Size     : " + file.length() + " bytes");
            }
        }
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top