0

我正在处理电子邮件附件。我在附件时遇到一个问题。问题是我想发送一封带有附件的邮件。我在这个路径上有一个文件 sdcard0 然后是 fgg 然后是 hh.html。当我对此进行调试时File file = new File(attachments.getString(i)); 它显示 文件: /storage/sdcard0/fgg/hh.html 但是在此之后它不去如果条件为什么?

File file = new File(attachments.getString(i));
                        if (file.exists()) {
                            Uri uri = Uri.fromFile(file);
                            uris.add(uri);
                        }

这是我的漏洞代码

JSONArray attachments = parameters.getJSONArray("attachments");
        if (attachments != null && attachments.length() > 0) {
            ArrayList<Uri> uris = new ArrayList<Uri>();
            //convert from paths to Android friendly Parcelable Uri's
            for (int i=0; i<attachments.length(); i++) {
                try {
                    File file = new File(attachments.getString(i));
                    if (file.exists()) {
                        Uri uri = Uri.fromFile(file);
                        uris.add(uri);
                    }
                } catch (Exception e) {
                    LOG.e("EmailComposer", "Error adding an attachment: " + e.toString());
                }
            }
            if (uris.size() > 0) {
                emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
            }
        }
    } catch (Exception e) {
        LOG.e("EmailComposer", "Error handling attachments param: " + e.toString());
    }
4

3 回答 3

1

Uri 到文件将需要三斜杠:

file:///storage/sdcard0/fgg/hh.html

正如你在这里看到的。但我可能无法正常工作,因此请尝试删除字符串的“文件:”部分:

File file = new File(attachments.getString(i).replace("file:","");
于 2013-07-31T07:57:46.743 回答
1

在 URI 中,您有不同的部分。

先说方案:

  • http://
  • 文件://
  • ftp://

然后是你要访问的路径:

  • 我的文件.txt
  • 视频/myvideo.avi
  • /storage/sdcard0/fgg/hh.html

所以你的完整 URI 应该是:

file:///storage/sdcard0/fgg/hh.html

更多信息在这里:

http://developer.android.com/reference/java/net/URI.html

然后,您可以构建您的文件并使用此代码段检查它是否存在

Uri.Builder builder = new Uri.Builder();
builder.scheme("file");
builder.path(myFilePath);
Uri uri = builder.build();
File file = new File(uri.getPath());
if (file.exists()) {
    uris.add(uri);
    // do whatever you want
}

编辑:

如果您的 JSON 向您发送完整的 URI 路径,请改用以下代码:

Uri uri = Uri.parse(attachments.getString(i));
File file = new File(uri.getPath());
if (file.exists()) {
    uris.add(uri);
    // do whatever you want
}
于 2013-07-31T08:22:02.847 回答
0

Try two forward slashes after :

file://storage/sdcard0/fgg/hh.html

edit:

should be 3 forward slashes

于 2013-07-31T07:51:35.813 回答