Java 如何在Android KitKat上创建.txt文件并发送电子邮件

Java 如何在Android KitKat上创建.txt文件并发送电子邮件,java,android,android-studio,android-4.4-kitkat,Java,Android,Android Studio,Android 4.4 Kitkat,所以我已经尝试了一天在SD卡上创建一个.txt文件,结果发现不是我的代码错了,但是KitKat不再允许开发者在外部SD卡上存储文件;是否有一个临时的.txt文件,或者一些新的代码来创建一个文件然后发送它? 这是我当前无法使用的代码 String DataIn = PhoneNumber + "," + dataLong + "," + dataLat; try { File storageDirectory = new File ("/sdcar

所以我已经尝试了一天在SD卡上创建一个.txt文件,结果发现不是我的代码错了,但是KitKat不再允许开发者在外部SD卡上存储文件;是否有一个临时的.txt文件,或者一些新的代码来创建一个文件然后发送它? 这是我当前无法使用的代码

 String DataIn = PhoneNumber + "," + dataLong + "," + dataLat;
        try
        {
        File storageDirectory = new File ("/sdcard/LocationData.txt");
            storageDirectory.createNewFile();
            FileOutputStream fout = new FileOutputStream(storageDirectory);
            OutputStreamWriter myoutwriter = new OutputStreamWriter(fout);
            myoutwriter.append(DataIn);
            myoutwriter.close();Toast.makeText(getBaseContext(),"Saved", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e)
        {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        Intent emailintent = new Intent(Intent.ACTION_SEND);
        emailintent.setType("text/plain");
        emailintent.putExtra(Intent.EXTRA_EMAIL, new String[]{"xxxxxxxx@xxxxxxxxx.com"});
        emailintent.putExtra(Intent.EXTRA_SUBJECT, "Data");
        emailintent.putExtra(Intent.EXTRA_TEXT, "Hello World!");
        File root = Environment.getRootDirectory();
        String DataAttachment = "/sdcard/LocationData.txt";
        File filer = new File(root, DataAttachment);
        if (!filer.exists() || filer.canRead())
        {
            return;
        }
        Uri uri = Uri.fromFile(filer);
        emailintent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(emailintent, "Choose an Email provider"));

我使用此代码在外部存储上创建.txt文件,并在所有版本上都可以正常工作

 File rootPath = new File(Environment.getExternalStorageDirectory(), DNAME);
    if(!rootPath.exists()) {
        rootPath.mkdirs();
    }
    File dataFile = new File(rootPath, FILENAME);
    if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(this, "Cannot use storage.", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    try {           
        FileOutputStream mOutput = new FileOutputStream(dataFile, false);
        String data = "DATA";
        mOutput.write(data.getBytes());
        mOutput.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
File dirs[]=ContextCompat.getExternalFilesDirs(getApplicationContext(),null);
String Info=“getExternalFilesDirs()\ndirs.length:+dirs.length;
int nr=-1;
而(++nr

您需要/Project/libs/android-support-v4.jar文件。

对于我来说,以下解决方案有效。 要创建文本文件,请使用以下命令

    File root = new File(DIRECTORY_PATH);
    File gpxfile = new File(root, "samples.txt");
    FileWriter writer = new FileWriter(gpxfile);
    writer.append("First string is here to be written.");
    writer.flush();
    writer.close();
电子邮件

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setData(Uri.parse("mailto:"));
    shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "email" });
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "test " +    "Subject");
    shareIntent.putExtra(Intent.EXTRA_TEXT, "test body");
    shareIntent.setType("application/octet-stream");
            shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://"+DIRECTORY_PATH+"/samples.txt"));
    startActivityForResult(Intent.createChooser(shareIntent, "Choose service"),EMAIL_ACTIVITY_REQUEST_CODE);

您好使用此方法在SD卡中存储文件:

 public void generateNoteOnSD(String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "hChat");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
如果要发送此文件,请使用以下地址

** File sd = Environment.getExternalStorageDirectory();
            File fileDir= new File(sd, "dir_path");
            Intent email = new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_STREAM, Uri.parse(fileDir.getAbsolutePath() + "/"
                            + "hchatDB.txt"));
                    startActivity(Intent.createChooser(email , "Email: Text File"));**

永远不要使用/sdcard这样的静态路径。而是使用getExternalStorageDirectory并创建您的文件夹。Kitkat仍然允许应用程序在可移动媒体上写入文件。但仅限于特定于应用程序的文件夹,如“/storage/1/Android/data/data//files”。您可以使用
getExternalFileDirs()
查找路径。它应该是其中之一。即使我这样做了,它也不会起作用,kitkat只是不让我给外部用户写信directory@greenapps你能给我举个例子吗?错误信息是什么?是的,所有版本都可以,但它不会在可移动媒体(如micro sd卡)上创建文件。相反,它将在外部内存中创建一个文件。对于SD卡,请使用此文件myFile=new文件(“/sdcard/mysdfile.txt”);myFile.createNewFile()但建议不要硬编码路径,所以我使用了上面的代码我得到了一条消息/存储/模拟。。。。当我在真正的设备上运行这个程序时,当我检查卡上没有创建一个文件时,我可以从sdk管理器中获取jar文件,或者我必须在线找到它吗?你可以在线找到它。
** File sd = Environment.getExternalStorageDirectory();
            File fileDir= new File(sd, "dir_path");
            Intent email = new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_STREAM, Uri.parse(fileDir.getAbsolutePath() + "/"
                            + "hchatDB.txt"));
                    startActivity(Intent.createChooser(email , "Email: Text File"));**