android - 无法从android缓存目录中获取文件

标签 android file caching audio uri

我在从 Android 应用程序的缓存文件夹中获取文件时遇到问题。这是我正在尝试但不起作用的方法:



    File cacheDir = getApplicationContext().getCacheDir();
    myFile = File.createTempFile("filename", ".mp3", cacheDir);

    ...
    // Here I have to code to initialize the file
    ...

    Log.i(LOG_TAG, "file.length = "+myFile.length());  // This logs correct info

    ...

    //File file = new File(myFile.getPath());
    //Log.i(LOG_TAG, "file.length() = "+file.length());  // This logs 0
    //Log.i(LOG_TAG, "file.name = "+file.getName());     // This is correct

    String fileURI = myFile.getPath();
    mediaPlayer.setDataSource(fileURI);
    mediaPlayer.prepare();             // This crashes


如您所见,该文件似乎不包含任何内容。但是,我尝试用这段代码交换前两行,然后就可以了。

    myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MYFOLDER/filename.mp3");

我还没有找到任何方法在没有 URI 的情况下设置我的 mediaPlayer,当我尝试从 URI 获取文件时,它似乎是一个问题。

关于如何从缓存目录中获取文件,你们有解决方案吗?

最佳答案

好的,我设法自己找到了解决方案。首先,我可以通过更改 createTempFile 来向文件“添加内容”:

myFile = new File(getFilesDir(), "filename.mp3");

不幸的是,您似乎无法从该目录读取文件。您可以阅读更多相关信息 here .

因此我找到了this发布,我设法解决了它。这是我的最终代码:



     myFile = new File(getFilesDir(), "filename.mp3");

     ...

     Button playBtn = (Button) findViewById(R.id.button_play);
     playBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             play(myFile);
         }
     });

                    ...

        public void play(File f) {
            try {
                FileInputStream fis = new FileInputStream(f);
                mediaPlayer.setDataSource(fis.getFD());
                mediaPlayer.prepare();
                mediaPlayer.start();
                     ...


如果你不能传文件,那我也帮不了你。但是请在找到解决方案后发布。

关于android - 无法从android缓存目录中获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29413656/

相关文章:

java - 将 json 解析值与用户输入的值进行匹配

java - 在 AndroidManifest 中注册的 BroadcastReceiver 不工作

c++ - 从同一文件构造基类和继承类

caching - 读取 CPU 缓存内容

azure - 在 Service Fabric 集群上发布应用程序后 HttpContext.Session 为空

java - 使用 Spring/EHCache 在负载下刷新缓存

android - 来自 adb shell dumpsys 的 PackageSignatures

Android 9-补丁太多列和行?

c# - 在用户未登录时将文件复制到映射的驱动器(计划任务)

java - Symmetricds 动态更改文件同步的源基目录