4this
4this

Reputation: 759

How to get a certain part from file path that being saved as a String - Android / Java

I"m saving a file path as a String -

 String selectedPath1 = getPath(selectedImageUri);

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

Now i'm the selectedPath1 String is shown like that -

/storage/emulated/0/DCIM/Camera/201403_231.jpg

Now what iwould like to do is to save the - 201403_231.jpg - as a separate String.

So how can i "cut" it from the String?

Thanks for any kind of help

Upvotes: 0

Views: 89

Answers (4)

AndyFaizan
AndyFaizan

Reputation: 1893

selectedPath1.substring(selectedPath1.lastIndexOf('/') + 1)

This would return the file name.

Upvotes: 0

Holloway
Holloway

Reputation: 7367

Does android not have the File type that java has?

String filename = new File(uri).getName();

Upvotes: 2

Adam Stelmaszczyk
Adam Stelmaszczyk

Reputation: 19837

You can use this regular expression: [^/]*$. Example:

String mydata = "/storage/emulated/0/DCIM/Camera/201403_231.jpg";
Pattern pattern = Pattern.compile("[^//]*$");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
    System.out.println(matcher.group(0));
}

Output:

201403_231.jpg

Upvotes: 0

Szymon
Szymon

Reputation: 43023

Use substring() and lastIndexOf() methods. Note that you need to add 1 to the last index to not take the / character.

String selectedPath1 = "/storage/emulated/0/DCIM/Camera/201403_231.jpg";
String lastPart = selectedPath1.substring(selectedPath1.lastIndexOf('/') + 1);

Output is 201403_231.jpg.

Upvotes: 2

Related Questions