TheHamstring
TheHamstring

Reputation: 732

Get the folder name of a files parent

I'm working with some code and I want it to behave differently depending on the folder name that the file is in. I don't need the absolute path just the final folder. Everything that I have seen so far is using a absolute path that is specified in the file.

Upvotes: 1

Views: 13760

Answers (5)

SeniorJD
SeniorJD

Reputation: 7212

Try java.io.File.getParentFile() method.

String getFileParentName(File file) {
    if (file != null && file.getParentFile() != null) {
        return file.getParentFile().getName();
    }
    return null; // no parent for file
}

Upvotes: 2

James Dunn
James Dunn

Reputation: 8284

This is what you want:

public static String getParentName(File file) {
    if(file == null || file.isDirectory()) {
            return null;
    }
    String parent = file.getParent();
    parent = parent.substring(parent.lastIndexOf("\\") + 1, parent.length());
    return parent;      
}

Unfortunately there is no pre-provided method that just returns the name of the last folder in the file's path, so you have to do some String manipulation to get it.

Upvotes: 7

Ankit Rustagi
Ankit Rustagi

Reputation: 5637

String path = "/abc/def"; // path to the directory  
try
{
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();

    for (File file : listOfFiles) 
    {
      if(file.isDirectory())
      {
        switch(file.getName)
        {
             case "folder1" : //do something
              break
             case "folder2" : //do something else 
              break
        }  
      }
    }
}   
catch(Exception e) 
{
      System.out.println("Directory not Found"); 
}

Upvotes: 0

Jost
Jost

Reputation: 1534

I think java.io.File.getParent() is what you are looking for:

import java.io.File;

public class Demo {

   public static void main(String[] args) {
      File f = null;
      String parent="not found";
      f = new File("/tmp/test.txt");
      parent = f.getParent();
      System.out.print("parent name: "+v);
   }

}

Upvotes: 2

shieldgenerator7
shieldgenerator7

Reputation: 1756

There's

String File.getParent()

There's also

File File.getParentFile()

I don't know what the return in terms of being absolute or relative, but if it's absolute you can always find the last (or second to last, depending) instance of the "\" character (remember to escape it like this "\\") to denote where the lowest folder level is.

For example, if the function returned:

"C:\Users\YourName" is where you'd get the last occurance of "\", and all characters after it would be the folder you want

"C:\Users\YourName\" is where you'd get the second to last occurance of "\", and all characters between that and the last "\" would be the folder you're looking for.

Java File API: http://docs.oracle.com/javase/7/docs/api/java/io/File.html

Upvotes: 1

Related Questions