[英]Get the directory from a file path in java (android)
Is there a function to get the directory part of a file path? 是否有一个函数来获取文件路径的目录部分?
so from 所以
String a="/root/sdcard/Pictures/img0001.jpg";
you get 你得到
"/root/sdcard/Pictures"
Yes. 是。 First, construct a File
representing the image path: 首先,构造一个表示图像路径的File
:
File file = new File(a);
If you're starting from a relative path: 如果你从相对路径开始:
file = new File(file.getAbsolutePath());
Then, get the parent : 然后, 得到父母 :
String dir = file.getParent();
Or, if you want the directory as a File
object, 或者,如果您希望将目录作为File
对象,
File dirAsFile = file.getParentFile();
A better way, use getParent()
from File
Class.. 更好的方法是,使用File
Class中的getParent()
。
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
http://developer.android.com/reference/java/io/File.html#getParent%28%29 http://developer.android.com/reference/java/io/File.html#getParent%28%29
You could also use FilenameUtils from Apache . 您也可以使用Apache的FilenameUtils 。 It provides you at least the following features for the example C:\\dev\\project\\file.txt: 它为示例C:\\ dev \\ project \\ file.txt提供了至少以下功能:
I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java): 我在4天后得到了解决方案,请注意以下几点,同时给出Android(Java)中File类的路径:
mention permissions in Manifest file. 在Manifest文件中提及权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
eg 例如
File file=new File(path);
long=file.length();//in Bytes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.