简体   繁体   中英

Recursively Deleting Class Files

So I'm trying to create a program in Unix that will take in a directory as a parameter and then recursively go through, open all of the folders, look through all of the files, and then delete all of the class files. I thought I was taking the correct steps as I was given code for a similar program and told to use it as a basis, but upon testing my program and I discover that nothing happens.

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;

public class ClassFileDeleter {
    public static void main(String[] args) throws ParseException {
    String dirName = args[0];
    deleteFile(dirName);
}

private static void deleteFile(String dirName) {
    Path path = Paths.get(dirName);
    File dir = path.toFile();

    if(dir.exists()) {
    File[] files = dir.listFiles();
    if(dir.isDirectory()) {
    for(File f:files) {
    if(!f.isDirectory())
            if(f.toString().endsWith(".class"))
            System.out.println("yes");
            else deleteFile(dirName + "/" + f.getName());

    }}}
    }}

I am at a loss at what I should do. I haven't attempted to delete anything yet because I don't want to delete anything that isn't a class file so I am using some dummy code that should print 'yes' once the program finds a class file. However when I run my code, absolutely nothing happens. I believe that there is either an issue with the way I am searching for class files (We are supposed to use endsWith) or with the way I am attempting to use recursion to look through all of the files in the specified directory. If I could have some assistance, that would be great.

I would start with a isFile check (and then test the extension of a file and log it if it matches), then you could recursively descend any directories. Something like,

private static void deleteFile(String dirName) {
    File dir = new File(dirName);
    if (dir.isFile()) {
        if (dir.getName().endsWith(".class")) {
            try {
                System.out.println("Delete: " + dir.getCanonicalPath());
                // dir.delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else if (dir.isDirectory()) {
        File[] files = dir.listFiles();
        for (File f : files) {
            try {
                deleteFile(f.getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

It strikes me that the code that you have to recurse through the directory, is creating a file object not a directory.

A quick google gave me this from the Oracle java tutorial ( http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#listdir ).

Listing a Directory's Contents

You can list all the contents of a directory by using the newDirectoryStream(Path) method. This method returns an object that implements the DirectoryStream interface. The class that implements the DirectoryStream interface also implements Iterable, so you can iterate through the directory stream, reading all of the objects. This approach scales well to very large directories. Remember: The returned DirectoryStream is a stream. If you are not using a try-with-resources statement, don't forget to close the stream in the finally block. The try-with-resources statement takes care of this for you.

The following code snippet shows how to print the contents of a directory:

Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path file: stream) {
        System.out.println(file.getFileName());
    }
} catch (IOException | DirectoryIteratorException x) {
    // IOException can never be thrown by the iteration.
    // In this snippet, it can only be thrown by newDirectoryStream.
    System.err.println(x);
}

The Path objects returned by the iterator are the names of the entries resolved against the directory. So, if you are listing the contents of the /tmp directory, the entries are returned with the form /tmp/a, /tmp/b, and so on.

This method returns the entire contents of a directory: files, links, subdirectories, and hidden files. If you want to be more selective about the contents that are retrieved, you can use one of the other newDirectoryStream methods, as described later in this page.

Note that if there is an exception during directory iteration then DirectoryIteratorException is thrown with the IOException as the cause. Iterator methods cannot throw exception exceptions.

So I'd take a look there and see what you can work out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM