开发者

Get dir of a file

I think I have a simple question, but I cant figure it out. I would like to get the directory of a file.

Example: path = /mnt/sdcard/music/music.mp3

Should return 'music'

public String getDir(String pathAudioFile)
{
    File f = new File(pathAudioFile);

    retu开发者_运维问答rn  f.???
}


f.getParent(); // returns directory String
f.getParentFile(); // returns File directory object


f.getParentFile().getName()

will return just "music", stripping off the leading path elements.


Here you go

File file = new File(pathAudioFile);
String parent = file.getParent();
System.out.println("Parent directory is : " + parent);


public String getDir(String pathAudioFile)
..
    return  f.getParent();

But the code should not be return a String that represents a File. It should return a File. 1

public File getDir(String pathAudioFile)
..
    return  f.getParentFile();

1 IMO all methods in the J2SE that are designed to accept a String that represents a File should be deprecated. If a method needs a File, give it a File!


Extending that philosophy..

@deprecated Use getDir(java.io.File) instead.
public File getDir(String pathAudioFile)
{
    return  getDir(new File(pathAudioFile));
}

public File getDir(File audioFile)
{
    return  audioFile.getParentFile();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜