Reda
Reda

Reputation: 468

Hard coding part of the Path in Java

I have the following dir tree

C:\folder1\folder2\SPECIALFolders1\folder3\file1.img
C:\folder1\folder2\SPECIALFolders2\folder3\file2.img
C:\folder1\folder2\SPECIALFolders3\folder3\file3.img
C:\folder1\folder2\SPECIALFolders4\folder3\file4.img
C:\folder1\folder2\SPECIALFolders5\folder3\file5.img

I want to get to folder2, list all dirs in it (SpecialFolders) then retrieve the paths of those folders while adding (folder3) to their path

The reason I'm doing this is I want later to pass this path (paths) to a method to retrieve last modified files in folder3. I know there are way easier ways to do it but this is a very particular case.

I'm also trying to retrieve those folders within a specific time range so I used a while loop for that

        Date first = dateFormat.parse("2015-6-4");
        Calendar ystr = Calendar.getInstance();
        ystr.setTime(first);

        Date d = dateFormat.parse("2015-6-1");
        Calendar last = Calendar.getInstance();
        last.setTime(d);

        while(last.before(ystr)) 
        {
            //fullPath here = "C:\folder1\folder2\"
            File dir = (new File(fullPath));
            File[] files = dir.listFiles();

            for (File file : files) 
            {
                //Retrieve Directories only (skip files)
                if (file.isDirectory()) 
                { 
                    fullPath = file.getPath();
                    //last.add(Calendar.DATE, 1);
                    System.out.println("Loop " + fullPath);
                }
            }

        }
        fullPath += "\\folder3\\";
        return fullPath;

The problem with my code is that it only returns one path (that's the last one in the loop) --which make sense but I want to return all of the paths like this

C:\folder1\folder2\SPECIALFolders1\folder3\
C:\folder1\folder2\SPECIALFolders2\folder3\
C:\folder1\folder2\SPECIALFolders3\folder3\
C:\folder1\folder2\SPECIALFolders4\folder3\
C:\folder1\folder2\SPECIALFolders5\folder3\

I appreciate your input in advance

Upvotes: 0

Views: 374

Answers (1)

m.cekiera
m.cekiera

Reputation: 5395

Instead of fullPath String, use for example ArrayList<String> to store all paths. Than instead of:

fullPath = file.getPath();

use:

yourArrayList.add(file.getPath());

Your method will return an ArrayList with all paths, and you will need to code a method to retrive all paths from it.

Upvotes: 1

Related Questions