我有一段代码,用来检查mediastore.audio.media内容提供商的SD卡中是否存储了MP3文件
问题是不管情况如何。SD卡上是否存在路径名存储在变量“audiofilename”中的文件。它总是返回“这个文件不存在”作为结果。尽管变量audiofilename的字符串路径名存储在“/mnt/sd card/music/jungle.mp3”中,但这个mp3文件实际上是存储在sd卡上的。通过吐司信息和检查SD卡内容很容易证明。
我可能在使用文件或环境类时出错。有人能在这里显示的代码中看到问题吗?

 // 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();

最佳答案

尝试更改此行

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();

希望对你有帮助。
谢谢。

07-24 09:47
查看更多