【发布时间】:2015-09-28 20:56:22
【问题描述】:
我有三段代码:一段设置文件的原始文件路径,一段用于重命名文件,另一段用于匹配文件以便播放文件(录音)。
我的问题是,据我所知以及我能够在网上找到的信息,当我重命名文件路径时,我需要在文件路径的其余部分之前使用“file://”...否则 MediaPlayer当我尝试播放时抛出异常。经过大量搜索,我没有想出一种使它们统一的好方法,以便“匹配器”代码可以在所有文件上工作。我最好的猜测是,如果我能找到一种不必在文件路径的其余部分之前使用“file://”的方法,那将是理想的。
1) 设置原始文件路径的代码:
public void setFileNameAndPath(){
int count = 0;
File f;
do{
count++;
mFileName = getString(R.string.default_file_name)
+ " #" + (mDatabase.getCount() + count) + ".mp4";
mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
mFilePath += "/SoundRecorder/" + mFileName;
f = new File(mFilePath);
}while (f.exists() && !f.isDirectory());
}
2) 重命名文件路径:
public void rename(int position, String name) {
//rename a file
String mFilePath = "file://" + Environment.getExternalStorageDirectory().getAbsolutePath();
mFilePath += "/SoundRecorder/" + name;
File f = new File(mFilePath);
if (f.exists() && !f.isDirectory()) {
//file name is not unique, cannot rename file.
Toast.makeText(mContext,
String.format(mContext.getString(R.string.toast_file_exists), name),
Toast.LENGTH_SHORT).show();
} else {
//file name is unique, rename file
File oldFilePath = new File(getItem(position).getFilePath());
oldFilePath.renameTo(f);
mDatabase.renameItem(getItem(position), name);
notifyItemChanged(position);
}
}
3) 匹配文件:
Intent iin = getIntent();
Bundle b = iin.getExtras();
newString = (String) b.get("filename");
mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
mFilePath += "/SoundRecorder/" + newString;
【问题讨论】:
-
file://的实际问题是什么?即使您尽您所知需要它,您是否尝试过?file://很少需要,因为以/开头的所有内容都是一个普通文件,大多数代码都会知道这一点。 -
我必须使用 file:// 来允许播放每个录音。我试过没有它..它不播放但有暂停按钮,然后当我按下暂停时,它在录制结束时,然后当我按下播放时,应用程序崩溃(通常它只是再次播放)。我在我无法再次找到的 stackoverflow 答案中找到了该解决方案。问题是一组录音以“file://”开头而另一组没有,我将名称的结尾发送为 putExtra,我只能有一个文件路径字符串。
-
如果路径以
/开头,添加file://怎么样?`那么你一切都一样 -
然后它以非法状态异常失败。
-
Tbh,你的主要问题似乎是一个凌乱的代码库,而不是 file:// 或没有 file:// - 我仍然不明白哪里/为什么你不能解决问题简单的字符串操作,例如检查 file://,然后添加或删除它。
标签: android file android-studio filepath