试图将创建的文本文件作为电子邮件附件从默认文件夹发送



我正在尝试一些简单的创建一个文本文件,然后将其作为附件发送。虽然它工作得很好,如果我使用sd卡,我不知道在哪里把它放在"标准数据文件夹",所以我的应用程序实际上适用于每个人没有sd卡(和文件是不可见的)

当这段代码工作时,我把问题放在<- *注释中。

创建文件时:

String FILENAME = "myFile.txt";
    String string = "just something";
    // create a File object for the parent directory
    File myDirectory = new File("/sdcard/myDir/");  // ******** <- what do I have to put HERE for standard data folder????
    // have the object build the directory structure, if needed.
    myDirectory.mkdirs();
    // create a File object for the output file
    File outputFile = new File(myDirectory, FILENAME);
    // now attach the OutputStream to the file object, instead of a String representation
    FileOutputStream fos = null;
   //always have to put try/catch around the code - why? I don't know
    try {
        fos = new FileOutputStream(outputFile);
    } catch (FileNotFoundException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
     //again have to put try/catch around it - otherwise compiler complains
    try {
        fos.write(string.getBytes());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

发送文件时:

public void doSendFile() {
    String fileName = "/sdcard/myDir/myFile.txt"; // ******** <- what do I have to put HERE for standard data folder????
    Intent i = new Intent(Intent.ACTION_SEND);
    try {
        mainDataManager.logFileHandle.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    i.setType("text/plain");
    i.putExtra(Intent.EXTRA_EMAIL, new String[] { "to@someone.com" });
    i.putExtra(Intent.EXTRA_SUBJECT, "subject");
    i.putExtra(Intent.EXTRA_TEXT, "text");
    Log.i(getClass().getSimpleName(),
        "logFile=" + Uri.parse("file://" + fileName));
    i.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + fileName));
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(getBaseContext(),
            "There are no email clients installed.", Toast.LENGTH_SHORT)
            .show();
    }
    }

我发现文件似乎存储在"data/data/com.xxx.xxxx/databases/myFile.txt"创建时。但是当我在附件中使用这个时,什么也没有发送。

所以基本上我所需要的就是知道如何在本地内存中存储一个文件然后从那里发送它。因为不是每个人都有外置sd卡——我想。

谢谢!

这是因为SD卡没有受到保护,所以您可以像以前那样用标准的java方式写入。

为了写入Android文件系统,你不能使用这个,因为每个文件都使用应用程序密钥来保护,以避免其他应用程序使用它。

你应该使用openFileOutput()查看本教程获取更多信息:

http://www.anddev.org/working_with_files-t115.html

最新更新