Android 从路径中获取文件名

转载:http://androidstudy.iteye.com/blog/787560

方法一:利用String类

public String getFileName(String pathandname){
	int start=pathandname.lastIndexOf("/");
    int end=pathandname.lastIndexOf(".");
    if (start!=-1 && end!=-1) {
        return pathandname.substring(start+1, end);	
    }
    else {
        return null;
    }
}


方法二:利用正则表达式


String regEx=".+\\\\(.+)$";
    String str="C:\\Documents and Settings\\Administrator\\My Documents\\myfile.txt";
    Pattern p=Pattern.compile(regEx);
    Matcher m=p.matcher(str);
    boolean rs=m.find();
    if(rs){
       for(int i=1;i<=m.groupCount();i++) {
           System.out.println(m.group(i)); //括号内匹配内容
       }
   }


你可以使用以下方法来根据文件名获取文件路径: 1. 遍历设备上的文件系统,搜索匹配的文件名。 ```java public String getFilePathByFileName(String fileName) { File rootDir = Environment.getExternalStorageDirectory(); // 获取外部存储根目录 String filePath = searchFile(rootDir, fileName); return filePath; } private String searchFile(File file, String fileName) { if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { for (File child : files) { String filePath = searchFile(child, fileName); if (filePath != null) { return filePath; } } } } else { if (file.getName().equals(fileName)) { return file.getAbsolutePath(); } } return null; } ``` 2. 使用 ContentResolver 查询匹配的文件。 ```java public String getFilePathByFileName(String fileName, Context context) { Uri uri = MediaStore.Files.getContentUri("external"); String[] projection = {MediaStore.Files.FileColumns.DATA}; String selection = MediaStore.Files.FileColumns.DISPLAY_NAME + "=?"; String[] selectionArgs = {fileName}; Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA); String filePath = cursor.getString(columnIndex); cursor.close(); return filePath; } return null; } ``` 这两种方法分别通过遍历文件系统和查询 ContentResolver 来获取文件路径。注意,在使用这些方法之前,确保你已经获取了相应的权限,例如读取外部存储的权限。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值