3

我有一段代码应该检查 mp3 文件是否存储在 MediaStore.Audio.Media 内容提供商的 SD 卡中

问题是,无论情况如何。SD卡上是否存在路径名存储在变量“audioFilename”中的文件。它总是返回“此文件不存在”作为结果。尽管变量audioFilename 中存储了String 路径名“/mnt/sdCard/Music/Jungle.mp3”,而这个MP3 文件实际上是在SD 卡上。通过 Toast 消息和检查 SD 卡内容很容易证明。

我可能在使用 File 或 Environment 类时出错。任何人都可以在此处显示的代码中看到问题吗?

 // toast message to prove that the audioFilename is not null,
 // message displayed is the string, "File name: /mnt/sdCard/Music/Jungle.mp3"

 Toast.makeText(Editor.this, "File name: " + audioFilename,
 Toast.LENGTH_LONG).show();

 // the code below always returns "this file does not exist"

 File extStore = Environment.getExternalStorageDirectory();
 File myFile = new File(extStore.getAbsolutePath() + "audioFilename");

 if(myFile.exists()){

 Toast.makeText(Editor.this, "<<<< this file exists, it is: "+audioFilename+" >>>>",
 Toast.LENGTH_LONG).show();

 } else if(!myFile.exists()){

 Toast.makeText(Editor.this, "<<<< this file does not exist >>>> ",
 Toast.LENGTH_LONG).show();
 }

 Toast.makeText(Editor.this, "audio file name is: "+ audioFilename,
 Toast.LENGTH_LONG).show();
4

4 回答 4

3

你确定有 import java.io.File 吗?

尝试:

String pathsd = Environment.getExternalStorageDirectory()+"/";
// so var pathsd will return "/mnt/sdcard/"
// then you must sure var audioFilename is Music/Jungle.mp3
File myFile = new File(pathsd + audioFilename);

或者你确定你的路?如果您不确定可以尝试提供直接字符串路径。

File myFile = new File("/mnt/sdCard/Music/Jungle.mp3");
于 2012-12-19T05:52:55.637 回答
2

尝试更改此行

File myFile = new File(extStore.getAbsolutePath() + "audioFilename");

File myFile = new File(audioFilename);

我已经用相同的代码运行了测试,它运行良好。

这是我测试的代码:

String audioFilename =  "/sdcard/NewFolder/test1.jpg";

Toast.makeText(SimpleTest.this, "File name: " + audioFilename,
Toast.LENGTH_LONG).show();

// the code below always returns "this file does not exist"

File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(audioFilename);

if(myFile.exists()){

    Toast.makeText(SimpleTest.this, "<<<< this file exists, it is: "+audioFilename+" >>>>",
    Toast.LENGTH_LONG).show();

} else if(!myFile.exists()){

    Toast.makeText(SimpleTest.this, "<<<< this file does not exist >>>> ",
    Toast.LENGTH_LONG).show();
}

Toast.makeText(SimpleTest.this, "audio file name is: "+ audioFilename,
Toast.LENGTH_LONG).show();

希望它可以帮助你。

谢谢。

于 2012-12-19T05:53:15.107 回答
0

您需要在 AndroidManifeast 文件中添加权限

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

编辑 :

File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore+ "/Music/Jungle.mp3"); <---- try this
于 2012-12-19T05:47:06.177 回答
0

我只是冒险猜测并假设您正在使用物理设备来测试您的应用程序。如果这是真的,您的外部存储可能没有安装(因为您在计算机上使用 USB 存储),因此根据系统该文件确实不存在。尝试在没有插入 USB 线的情况下测试您的代码。

编辑: 删除“audioFilename”周围的引号。

File myFile = new File(extStore.getAbsolutePath() + "audioFilename");

File myFile = new File(extStore.getAbsolutePath() + audioFilename);
于 2012-12-19T05:47:50.063 回答