简体   繁体   中英

Recursion: Checking for files in Directories and reading them

Before you speculate something like "This guy is asking for homework help", I'll go ahead and clear any doubts you may have and say yes, this is related to homework. However, I hope that does not take away from the learning that this question provides to me and/or anyone who reads this in the future.

Background : We're currently working on recursion and our assignment asks that we write a program that uses command arguments to check a directory and its file contents for a string(that is also a command argument). We must use recursion for this.


-I want to make this clear that I UNDERSTAND WHAT THE ASSIGNMENT IS ASKING I am simply asking, how would this work recursively because I just don't get it.

We did a problem where we had to find the size of a directory and it made sense, but I don't get how to check if something is a directory or file and based on that we read its contents or go deeper into the directory until we find a file.


Here's what I've currently done. Not too sure how wrong this is as I'm basing entirely off of the 'check the size of a directory' assignment we previously did:

The folder that I'm checking is something like this: Directory ---> files --inside main directory --->> Two directories ----> files within both of those directories

public class SearchingForStrings {

public static void main(String[] args) {
    String path = "."; // default location of this project
    File sf = new File(path);
    String mysteriesDirectory = args[0];
    String keyString = args[1];

    countLinesWithString(sf, mysteriesDirectory, keyString);
}

public static int countLinesWithString(File startPath, String mysteriesDirectory, String keyString) {
    if(!startPath.exists()) {
        throw new IllegalArgumentException("File " + startPath + " does not exist!");
    } else if(startPath.isFile()) {
        return Integer.parseInt(startPath.getAbsolutePath()); // Just to show where the file is I located the parsing is just to stop an error from flagging on this part; Going to ask professor if it's okay with him


        // this is where we would begin reading the contents of the files
    } else if(startPath.isDirectory()) {
        // This is where our recursion would take place: essentially
        // we will be going 'deeper' into the directory until we find a file

        //File[] subFiles = startPath.listFiles();
        countLinesWithString(startPath, mysteriesDirectory, keyString);
    } else {
        throw new IllegalStateException("Unknown file type: " + startPath);
    }

}

}

In short: Could someone explain how recursion would work if you wanted to go deeper into a director(y/ies)?

I'll give this a try. It's something that is easier to explain than to understand.

The recursive method, on which you have made a decent start, might be documented as follows:

"For a given directory: for each file in the directory, count all the lines which contain a given string; for each directory in the directory, recurse".

The recursion is possible - and useful - because your original target is a container, and one of the types of things it can contain is another container.

So think of the counting method like this:

int countLines(dir, string)  // the string could be an instance variable, also, and not passed in
{
  var countedLines = 0;
  for each item in dir:
    if item is file, countedLines += matchedLinesInFile(item, string);
    else if item is dir, countedLines += countLines(item, string);
    else throw up;  // or throw an exception -- your choice
}

then call countLines from an exterior method with the original dir to use, plus the string.

One of the things that trips people up about recursion is that, after you get it written, it doesn't seem possible that it can do all that it does. But think through the above for different scenarios. If the dir passed in has files and no dirs, it will accumulate countedLines for each file in the dir, and return the result. That's what you want.

If the dir does contain other dirs, then for each one of those, you're going to call the routine and start on that contained dir. The call will accumulate countedLines for each file in that dir, and call itself for each dir recursively down the tree, until it reaches a dir that has no dirs in it. And it still counts lines in those, it just doesn't have any further down to recurse.

At the lowest level, it is going to accumulate those lines and return them. Then the second-lowest level will get that total to add to its total, and start the return trips back up the recursion tree.

Does that explain it any better?

Just help you get started with recursion check this : It will recursively go from base directory printing all the folders and files. Modify this to your requirements. Try and let us know.

import java.io.File;

public class Test {


    public static void getResource(final String resourcePath) {

        File file = new File(resourcePath);
        if (file.isFile()) {
            System.out.println("File Name : " + file.getName());
            return;
        } else {
            File[] listFiles = file.listFiles();
            if (listFiles != null) {
                for (File resourceInDirectory : listFiles) {

                    if (!resourceInDirectory.isFile()) {
                        System.out.println("Folder "
                                + resourceInDirectory.getAbsolutePath());
                        getResource(resourceInDirectory.getAbsolutePath());
                    } else {
                        getResource(resourceInDirectory.getAbsolutePath());
                    }

                }
            }

        }
    }

    public static void main(String[] args) {

        final String folderPath = "C:/Test";
        getResource(folderPath);
    }

}

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