我有一段代码可以检查一个mp3文件是否存储在MediaStore.Audio.Media内容提供商的SD卡中
问题在于无论情况如何。如果SD卡上存在具有存储在变量“audioFilename”中的路径名的文件。它总是返回“此文件不存在”作为结果。尽管变量audioFilename的字符串路径名存储在其中“/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();
答案 0 :(得分:3)
您确定要导入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");
答案 1 :(得分: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();
希望它对你有所帮助。
感谢。
答案 2 :(得分: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
答案 3 :(得分:0)
我只是冒险猜测并假设您正在使用物理设备来测试您的应用程序。如果是这样,可能无法安装外部存储(因为您在计算机上使用USB存储器),因此根据系统确实不存在该文件。尝试在没有插入USB线的情况下测试代码。
修改强> 删除“audioFilename”周围的引号。
File myFile = new File(extStore.getAbsolutePath() + "audioFilename");
到
File myFile = new File(extStore.getAbsolutePath() + audioFilename);