Search code examples
javafiledirectoryfile-read

Read multiple folders files java


I know how to read file one by one from a folder in java.But I want to know If I give a folder named Search and in Search folder it has 3 different folders named A,B,C and each folder has multiple text files.I want to read all files which has in A,B,C folder by giving folder name Search as user input.can it be possible? I am new in java.


Solution

  • Sure it is. This sounds like you want to walk a folder (meaning, you want to do something for every file in a given folder, and for every subfolder in that folder, and for every file in that subfolder, and for every subfolder in the subfolder, ad infinitum, until you've seen everything).

    You can handroll a recursive algorithm yourself using Files.newDirectoryStream, or, just use the existing API:

    Path folderToWalk = Paths.get("/path/to/folder");
    Files.walkFileTree(folderToWalk, new SimpleFileVisitor<Path>() {
      @Override public visitFile(Path f, BasicFileAttributes attrs) throws IOException {
        // this is invoked for _every_ file anywhere in the folder structure.
      }
    });
    

    You can also add methods that are called if a file cannot be visited (for example, because of access rights issues), as well as if you want to get directory names - see the API.

    Within visitFile, you can do whatever you want. For example, if you want to fully read the file into a string, you can invoke Files.readString(f);. See the Files API for all the stuff you can do*.

    *) You said 'I know how to read...' - it's possible you've learned the obsolete, outdated java.io.FileInputStream API. Don't use that - use the Files API. It is less boneheaded about errors and charset encoding, gives you more stuff (such as giving you access to the file owner's name and group, and softlinks), and more high-level API primitives, such as 'just read the whole thing into a string for me please', and, 'just walk this entire file tree for me please'.