【问题标题】:Making Android filepaths uniform使 Android 文件路径统一
【发布时间】: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


【解决方案1】:

我认为 file:// 是文件的 URI,例如在资源可以存在于本地存储 (file://) 或 Internet (http://) 上的媒体播放器中很有用

要将字符串“转换”为 URI,请使用

Uri uri = Uri.parse("http://www.google.com");

并将 URI “转换”为文件使用

File file = new File(uri.getPath());

【讨论】:

  • 你能解释一下我应该如何在我的情况下使用它吗?
  • 你写“我最好的猜测是,如果我能找到一种方法,在文件路径的其余部分之前不必使用“file://”,那将是理想的”你不应该使用file:// 前缀 (URI) 用于重命名文件,只需使用文件路径。但是,如果您想获取 URI (file://),因为它是您的媒体播放器所必需的,请使用 Uri uri = Uri.fromFile(filepath);
  • 如果它没有回答你的问题,请更新你的问题,因为我不明白你到底想要什么......
猜你喜欢
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
  • 2014-12-15
  • 2011-07-04
  • 2023-03-31
相关资源
最近更新 更多