Android 根据路径获取文件名

思路:

	利用String 类中的lastIndexOf()方法 , 分别获得"/" 和"."的索引,之后利用截取子串
substring(start , end)方法得到文件名。

/**
 * 根据路径获取文件名
 * @param path 路径参数
 * @return 文件名字符串
 */
private String splitVideoName(String path) throws Exception {
	// 判空操作必须要有 , 处理方式不唯一 , 根据实际情况可选其一 。
	if(path == null) {
            throw new Exception("路径不能为null"); // 处理方法一
 	    throw new RuntimeException("路径不能为null"); // 处理方法二
            toast 提示用户 // 处理方法三
	}

	int start=path.lastIndexOf("/");
	int end=path.lastIndexOf(".");
        if(start!=-1 && end!=-1){
		return path.substring(start+1,end);//包含头不包含尾 , 故:头 + 1
}else{
		return "";
//            return null; 返回 null 还是 "" 根据情况抉择吧  
	}
}

若有不当之处,敬请直言 !
完成此功能的方法不止三种 , 日后再追加 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用以下方法来根据文件名获取文件路径: 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、付费专栏及课程。

余额充值