不知道文件扩展名但知道完整文件名,如何打开文件?

4
 Intent tostart = new Intent(Intent.ACTION_VIEW);
                tostart.setDataAndType(Uri.parse(video_path+".***"), "video/*");
                startActivity(tostart);

假设我有一个文件路径

/mnt/sdcard/video/my_birthday_moovie001

'my_birthday_movie001' 可以是.mkv.mpg.mkv格式。我尝试在文件路径中添加“.***”,但仍无法打开该文件。

1
我真的不想扫描文件,因为我的目录中有很多文件,并且我已经在数据库中拥有没有扩展名的文件路径(不要问我为什么,我知道这是个坏主意)。 - artouiros
@Skizo 那听起来像是一个答案,如果没有其他更优美的方法。 - artouiros
也许尝试在循环中使用预定义的扩展名打开它?并捕获异常。如果没有抛出异常,那么你找到了你的扩展名。 - cylon
添加了一个回答 @artouiros ;) - Skizo-ozᴉʞS ツ
@artouiros 很抱歉回复晚了,但是你可以用这种方式得到精确的答案 :) - User Learning
显示剩余3条评论
5个回答

1

我看到你将路径存储在数据库中,但没有包含文件扩展名。由于存在很多扩展名,安卓无法自动选择正确的扩展名,因此你需要创建一种方法来检测扩展名。

以下是一种强大的方法,适用于你的情况,但在已知扩展名的情况下不建议使用。

public String chk_path(String filePath)
{
//create array of extensions
String[] ext=new String[]{".mkv",".mpg"}; //You can add more as you require

//Iterate through array and check your path which extension with your path exists

String path=null;
for(int i=0;i<ext.Length;i++)
{
  File file = new File(filePath+ext[i]);
  if(file.exists())
    { 
     //if it exists then combine the extension
     path=filePath+ext[i];
     break;
    }
}
return path; 
}

现在在你的代码中播放一首歌。
if(chk_path(video_path)!=null)
{
 Intent tostart = new Intent(Intent.ACTION_VIEW);
                tostart.setDataAndType(Uri.parse(video_path), "video/*");
                startActivity(tostart);
}
else
 //tell user that although the path in database but file on this path do not exists

1

好的,我加上了注释。

你可以比较路径是否与任何文件名匹配(不包含扩展名),如果匹配,你就得到它了。

你可以简单地这样做:

获取目录路径

File extStore = Environment.getExternalStorageDirectory();

在我的示例中,我将文件名设置为unnamed,但您可以根据自己的喜好进行更改,例如my_birthday_moovie001

String NameOfFile = "unnamed";

添加视频,我将其放在“下载”中,但您可以更改它

String PathWithFolder = extStore + "/Download/";

创建一个方法,列出路径中的所有文件
private List<String> getListFiles(File parentDir) {
    ArrayList<String> inFiles = new ArrayList<String>();
    File[] files = parentDir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            inFiles.addAll(getListFiles(file));
        } else {
            String AbsolutePath = file.getAbsolutePath();
            //Get the file name ex : unnamed.jpg
            String nameofFile = AbsolutePath.substring(AbsolutePath.lastIndexOf("/") + 1, AbsolutePath.length());
            //Remove the .jpg --> Output unnamed
            String fileNameWithoutExtension = nameofFile.substring(0, nameofFile.lastIndexOf('.'));
            //Add each file
            inFiles.add(fileNameWithoutExtension);
        }
    }
    return inFiles;
}

通过这种方式,您可以获得文件的名称

List<String> files = getListFiles(new File(PathWithFolder));

只需添加一个 for 循环,查找您的 file 的匹配项即可。

for (int i = 0; i<=files.size()-1; i++){
   if(PathWithFolder.equals(files.get(i))) {
       Toast.makeText(MainActivity.this, "You got it!", Toast.LENGTH_SHORT).show();
   }
   else{
       Toast.makeText(MainActivity.this, "You don't.", Toast.LENGTH_SHORT).show();
    }
}

如果你想获取路径并执行@Zain Ul Abidin提出的建议,并在getListFiles()方法上进行比较,请添加以下内容:
String fileExtension = nameofFile.substring(nameofFile.lastIndexOf("."));

希望能有所帮助。


1
谢谢您提供的方法,但我发现@Zain Ul Abidin的答案会更快一些。(因为我的files.size()将返回一个带有3个零的数字)无论如何,还是非常感谢! - artouiros

0
你可以尝试这样做,首先获取文件名和扩展名,然后进行比较和实现。就像这样:
例如,文件名为04chamelon,扩展名为.png:
File f = new File("/mnt/storage/sdcard/Pictures/04chameleon");
        File yourDir = new File("/mnt/storage/sdcard/Pictures");
        nametwo = f.getName();
        for (File fa : yourDir.listFiles()) {
            if (fa.isFile())
                fa.getName();
            String path = fa.getName(); // getting name and extension
            filextension = path.substring(path.lastIndexOf(".") + 1); // seperating extension
            name1 = fa.getName();
            int pos = name1.lastIndexOf(".");
            if (pos > 0) {
                name1 = name1.substring(0, pos);
            }
        }
        if (name1.equals(nametwo)) {
            Intent tostart = new Intent(Intent.ACTION_VIEW);
            tostart.setDataAndType(Uri.parse(f + "." + filextension), "image/*");
            //tostart.setDataAndType(Uri.parse(f + "." + filextension), "video/*");
            startActivity(tostart);
        }

0

从另一个问题中:

考虑使用Apache Ant中的DirectoryScanner:

DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.java"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();

你需要引用ant.jar(对于ant 1.7.1大约1.3 MB)。

然后,运行文件数组并检查 如果files[i]包含(yourfile) yourfile= files[i]


0

使用最新的ContentResolver,您可以轻松地使用contentResolver.getType(uri)函数来检测文件类型。

private fun getIntentForFile(intent: Intent, filePath: String, context: Context): Intent { 
    val uri = FileProvider.getUriForFile(                                                  
        context,                                                                           
        context.applicationContext.packageName + ".fileprovider",                          
        File(filePath)                                                                     
    )                                                                                      
    intent.putExtra(Intent.EXTRA_STREAM, uri)                                              
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)                                 

    intent.setDataAndType(uri, context.contentResolver.getType(uri))                       
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                                        
    return intent                                                                          
}   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接