AndroidDev
AndroidDev

Reputation: 4559

How to get FolderName and FileName from the DirectoryPath

I have DirectoryPath:
data/data/in.com.jotSmart/app_custom/folderName/FileName
which is stored as a String in ArrayList

Like

ArrayList<String> a;
a.add("data/data/in.com.jotSmart/app_custom/page01/Note01.png");

Now from this path I want to get page01 as a separate string and Note01 as a separate string and stored it into two string variables. I tried a lot, but I am not able to get the result. If anyone knows help me to solve this out.

Upvotes: 5

Views: 35668

Answers (4)

user10445557
user10445557

Reputation:

For folder name: file.getParentFile().getName().

For file name: file.getName().

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240966

f.getParent()

Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

For example

    File f = new File("/home/jigar/Desktop/1.txt");

    System.out.println(f.getParent());// /home/jigar/Desktop
    System.out.println(f.getName());  //1.txt

Update: (based on update in question)

if data/data/in.com.jotSmart/app_custom/page01/Note01.png is valid representation of file in your file system then

for(String fileNameStr: filesList){
  File file = new File(fileNameStr);
  String dir = file.getParent().substring(file.getParent().lastIndexOf(File.separator) + 1);//page01
  String fileName = f.getName();
  if(fileName.indexOf(".")!=-1){
     fileName = fileName.substring(0,fileName.lastIndexOf("."));
   }
}

Upvotes: 15

AAnkit
AAnkit

Reputation: 27549

create a file with this path... then use these two methods to get directory name and file name.

file.getParent(); // dir name from starting till end like data/data....../page01
file.getName(); // file name like note01.png

if you need directory name as page01, you can get a substring of path u got from getparent.

Upvotes: 1

user1132648
user1132648

Reputation:

How about using the .split ?

answer = str.split(delimiter);

Upvotes: 0

Related Questions