【问题标题】:Android Intent to save email attachmentAndroid Intent 保存电子邮件附件
【发布时间】:2014-07-12 11:58:43
【问题描述】:

我收到带有自定义文件扩展名(实际上是 zip 文件)的电子邮件。

当我尝试从例如打开附件时K9 电子邮件应用程序并将其保存到我的应用程序的缓存目录,zip 文件被损坏,例如它不使用文件管理器打开

private void importData(Uri data) {
    Log.d(TAG, data.toString());
      final String scheme = data.getScheme();

      if(ContentResolver.SCHEME_CONTENT.equals(scheme)) {
        try {
          ContentResolver cr = getApplicationContext().getContentResolver();
          InputStream is = cr.openInputStream(data);
          if(is == null) return;

          StringBuffer buf = new StringBuffer();            
          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
          String str;
          if (is!=null) {                           
              while ((str = reader.readLine()) != null) {   
                  buf.append(str);
              }             
          }     
          is.close();

          File outputDir = getApplicationContext().getCacheDir(); // context being the Activity pointer
          Log.d(TAG, "outputDir: " + outputDir.getAbsolutePath());

          String fileName = "test_seed.zip";
          Log.d(TAG, "fileName: " + fileName);

          File zipFile = new File(outputDir, fileName);
          FileWriter writer = new FileWriter(zipFile);
          try {
              writer.append(buf.toString());
              writer.flush();
              writer.close();
          } catch (IOException e) {
              Log.d(TAG, "Can't write to " + fileName, e);
          } finally {
              Toast.makeText(getApplicationContext(), "Zip key file saved to SDCard.", Toast.LENGTH_LONG).show();
          }
          // perform your data import here…

        } catch(Exception e) {
            Log.d("Import", e.getMessage(), e);
        }
    }
}

Uri 字符串是

content://com.fsck.k9.attachmentprovider/668da879-32c8-4143-a3ec-e135d901c443/31/VIEW

这是我的意图过滤器:

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.EDIT" />
<category android:name="android.intent.category.DEFAULT" />
<data
    android:mimeType="application/*"
    android:host="*" 
    android:pathPattern=".*\\.odks" />
</intent-filter>

【问题讨论】:

    标签: android file save intentfilter


    【解决方案1】:

    您的 BufferedReader.readLine() 是问题所在;它假定您的文件是一个很好的人类可读文本文件,其中 \n 表示行尾。 Zip文件不是那样的。因此,请调用 InputStream 和 FileOutputStream 的 read() 和 write() 方法。

    类似的东西:

    byte[] buffer = new byte[1024];
    int n = 0;
    while ((n = infile.read(buffer)) != -1) {
        outfile.write(buffer, 0, n);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 2019-05-07
      • 2019-01-21
      • 1970-01-01
      相关资源
      最近更新 更多