2

Given a File object how can I create the path for saving it?

I tried file.mkdirs() but for example if the file's path is:

/mnt/sdcard/downloads/myapp/temp/song.mp3 

it also creates a folder named "song.mp3" inside temp.

How can I do it correctly?

4 Answers 4

3

use this code

File myDir=new File("/sdcard/Download");
myDir.mkdirs();
String fname = "Image.jpg";
File file = new File (myDir,fname);
Sign up to request clarification or add additional context in comments.

Comments

3

Just try:

file.getParentFile().mkdirs();

this will create the parent directory.

Comments

1

If I have understand correctly what you need is

File.getParent()

hope it helps

Comments

1

If you just want to extract the path you can use lastIndexOf:

String p = "/mnt/sdcard/downloads/myapp/temp/song.mp3";
System.out.println(p.substring(0,p.lastIndexOf('/')));

Of course, if you already have File object then getParent(), as suggested, will be easier.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.