Manoj Krishna
Manoj Krishna

Reputation: 347

Retrieve last substring and before last substring in a path

I have a folder having sub-directories and files in it.
I'm able to rename the file in a recursive manner. My problem is to get the last A.2 and PE0120A and write it in CSV.
If the path is static, then I will count the number of occurrences and will get the values, but I don't know how many sub-folders a folder may contain.

public static void dirTree(File dir) throws IOException 
{
    File[] subdirs=dir.listFiles();
    for(File subdir: subdirs) 
    {
        if (subdir.isDirectory()) 
        {
            dirTree(subdir);
        } 
        else 
        {
            doFile(subdir);
        }
    }
}

C:/f1/f2/f3/manoj/Manoj_Eclipse/PE0120A/A.2/filename.txt

the dir is the root directory through which it has to start my program enter image description here

Upvotes: 1

Views: 56

Answers (1)

Manoj Krishna
Manoj Krishna

Reputation: 347

the below code will get the last and last but one folder name. thanks for support guys.

String splitpath = file.getAbsolutePath(); 
String[] pathsplit = splitpath.split("\\\\"); 
int l = pathsplit.length; 
String version = pathsplit[l-2]; 
String foldname = pathsplit[l-3]; 
FileWriter writer = new FileWriter("C:/Users/username/Desktop/test_output.csv"); writer.append(vesioin); 
writer.append(foldername); 
writer.append(splitpath);

Upvotes: 1

Related Questions