Álvaro
Álvaro

Reputation: 2870

Obtain name from absolute path, substring from last slash, java android

I want to extract the name of an absolute path. If I have a string with the value /mnt/sdcard/Videos/Videoname, I want to save a string with the value Videoname.

The string is changing and I can't obtain previously the number of slashes. How could I split a substring from the last slash?

/mnt/sdcard/Videos/Videoname --> Videnoname

Upvotes: 19

Views: 33463

Answers (6)

ravz
ravz

Reputation: 978

String path = "/mnt/sdcard/Videos/Videoname"; // Your path

String fileName = new File(path).getName(); // you file name

Upvotes: 7

Zar E Ahmer
Zar E Ahmer

Reputation: 34360

Easiest way is

String path ="AnyDirectory/subFolder/last.htm";
int pos = path.lastIndexOf("/") + 1;

path.substring(pos, path.length()-pos);

Now you have the last.htm in the path string.

Upvotes: 2

Jeje Doudou
Jeje Doudou

Reputation: 1706

If you got if from a "File" object, you can get it with the method:

String fileName = myFile.getName();

If you got it from a simple String, you can use

String fileName = myString.substring(myString.lastIndexOf("/")+1);

Upvotes: 16

DareDevil
DareDevil

Reputation: 5349

But with a little more research, the following code works...

String[] Tokens = stringPath.split("\\\\");

You need to escape the "\" twice.

Upvotes: 1

dacwe
dacwe

Reputation: 43504

You should go via the File api. Quoted from the File.getName() documentation:

Returns the name of the file or directory denoted by this abstract pathname. This is just the last name in the pathname's name sequence. If the pathname's name sequence is empty, then the empty string is returned.

Example:

String name = new File("/mnt/sdcard/Videos/Videoname").getName();

Upvotes: 25

Adam Weishaupt
Adam Weishaupt

Reputation: 95

string a = "/foo/bar/target";
string words = a.Split("/")
string target = words[words.length-1]

Upvotes: 0

Related Questions