letter Q
letter Q

Reputation: 15405

Iterating through a directory in java

Hi right now I have the following method I am using to read one file at a time in a the same directory as the class that has this method:

private byte[][] getDoubleByteArrayOfFile(String fileName, Region region)
    throws IOException
{
    BufferedImage image = ImageIO.read(getClass().getResource(fileName));
    byte[][] alphaInputData =
        new byte[region.getInputXAxisLength()][region.getInputYAxisLength()];
    for (int x = 0; x < alphaInputData.length; x++)
    {
        for (int y = 0; y < alphaInputData[x].length; y++)
        {
            int color = image.getRGB(x, y);
            alphaInputData[x][y] = (byte)(color >> 23);
        }
    }
    return alphaInputData;
}

I was wondering how I can make it so that instead of having "fileName" as a argument I can but a directory name as a argument and then iterate through all of the files within that directory and perform the same operation on it. Thanks!

Upvotes: 1

Views: 4227

Answers (5)

user1543394
user1543394

Reputation: 11

It is rather simple, using the File#listFiles() which returns a list of files in the specified File, which must be a directory. To make sure that the File is a directory, simply use File#isDirectory(). The problem occurs where you decide how to return the byte buffer. Since the method returns a 2d buffer, it is necessary to use a 3d byte buffer array, or in this case a List seems to me like the best choice since an unknown number of files will exist in the directory in question.



    private List getDoubleByteArrayOfDirectory(String directory, Region region) throws IOException {
      File directoryFile = new File(directory);

      if(!directoryFile.isDirectory()) {
        throw new IllegalArgumentException("path must be a directory");
      }

      List results = new ArrayList();

      for(File temp : directoryFile.listFiles()) {
        if(temp.isDirectory()) {
          results.addAll(getDoubleByteArrayOfDirectory(temp.getPath(), region));
        }else {
          results.add(getDoubleByteArrayOfFile(temp.getPath(), region));
        }
      }
      return results;
    }

Upvotes: 1

Pankaj
Pankaj

Reputation: 5250

We can use recursion to process a directory with subdirectories also. Here I am deleting file one by one, you can call any other function to process it.

public static void recursiveProcess(File file) {
    //to end the recursive loop
    if (!file.exists())
        return;

    //if directory, go inside and call recursively
    if (file.isDirectory()) {
        for (File f : file.listFiles()) {
            //call recursively
            recursiveProcess(f);
        }
    }
    //call processing function, for example here I am deleting
    file.delete();
    System.out.println("Deleted (Processed) file/folder: "+file.getAbsolutePath());
}

Upvotes: 0

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26068

Here is a quick example that may help:

private ArrayList<byte[][]> getDoubleByteArrayOfDirectory(String dirName,
    Region region) throws IOException {
       ArrayList<byte[][]> results = new ArrayList<byte[][]>();
       File directory = new File(dirName);
       if (!directory.isDirectory()) return null //or handle however you wish
       for (File file : directory.listFiles()) {
           results.add(getDoubleByteArrayOfFile(file.getName()), region);
       }  
       return results;
}

Not exactly what you asked for since it's wrapping your old method rather than re-writing it, but I find it a bit cleaner this way, and leaves you with the option of still processing a single file. Be sure to tweak the return type and how to handle the region based on your actual requirements (hard to tell from the question).

Upvotes: 1

pickypg
pickypg

Reputation: 22332

If you are using Java 7, then you need to take a look at NIO.2.

Specifically, take a look at the Listing a Directory's Contents section.

Path dir = Paths.get("/directory/path");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path file: stream) {
        getDoubleByteArrayOfFile(file.getFileName(), someRegion);
    }
} 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);
}

Upvotes: 2

hd1
hd1

Reputation: 34667

You can, see the list and listFiles documentation for how to do this.

Upvotes: 0

Related Questions