从java(android)中的文件路径获取目录

tru*_*ru7 22 java directory android path

是否有一个函数来获取文件路径的目录部分?

所以

String a="/root/sdcard/Pictures/img0001.jpg";
Run Code Online (Sandbox Code Playgroud)

你得到

"/root/sdcard/Pictures"
Run Code Online (Sandbox Code Playgroud)

ζ--*_*ζ-- 47

是.首先,构造一个File代表图像路径:

File file = new File(a);
Run Code Online (Sandbox Code Playgroud)

如果你从相对路径开始:

file = new File(file.getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)

然后,得到父母:

String dir = file.getParent();
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望将目录作为File对象,

File dirAsFile = file.getParentFile();
Run Code Online (Sandbox Code Playgroud)

  • 如果你正在使用像`File f = new File("file.txt")这样的相对路径;``要知道`f.getParent()`将返回`null`,而不是父 (3认同)

use*_*305 11

一个更好的方法,使用getParent()File类..

String a="/root/sdcard/Pictures/img0001.jpg"; // A valid file path 
File file = new File(a); 
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null
Run Code Online (Sandbox Code Playgroud)

http://developer.android.com/reference/java/io/File.html#getParent%28%29