简体   繁体   English

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

[英]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提供了至少以下功能:

  • the prefix - C:\\ 前缀 - C:\\
  • the path - dev\\project\\ 路径 - 开发\\项目\\
  • the full path - C:\\dev\\project\\ 完整路径 - C:\\ dev \\ project \\
  • the name - file.txt 名称 - file.txt
  • the base name - file 基本名称 - 文件
  • the extension - txt 扩展名 - 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类的路径:

  1. Use path for internal storage String path="/storage/sdcard0/myfile.txt"; 使用路径进行内部存储String path =“/ storage / sdcard0 / myfile.txt”;
  2. path="/storage/sdcard1/myfile.txt"; 路径= “/存储/ sdcard1 / myfile.txt的”;
  3. mention permissions in Manifest file. 在Manifest文件中提及权限。

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

  4. First check file length for confirmation. 首先检查文件长度以确认。
  5. Check paths in ES File Explorer regarding sdcard0 & sdcard1 is this same or else...... 检查ES文件资源管理器中关于sdcard0和sdcard1的路径是否相同或者......

eg 例如

File file=new File(path);
long=file.length();//in Bytes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM