在外部microSD卡中创建文件夹或文件

时间:2017-03-30 11:15:31

标签: java android android-studio android-6.0-marshmallow

我到处寻找我的问题的答案,我确实找到了大量的答案,应该解决了我的问题,但我无法解决它。

我的目标是放一张128GB的SD卡并将文件写入其中(csv或文本)。 我试图在microSD卡中打开文件或文件夹,但它没有创建它。 也没有创建文件。我认为我得到的路径是:

Environment.getExternalStorageDirectory()

不是SD卡路径。

这是我的java代码:

package com.example.thermie.test2;

import android.Manifest;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;


            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();


            String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
            //create folder
            File folder = new File(dir); //folder name
            boolean result = folder.mkdirs();

            //create file
            File file = new File(dir, "filename.txt");

            if (result){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(dir);
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}

我的目录是:/ storage / emulated / 0 / myDirectory 哪个不在我的SD卡中,它是没有任何访问权限的目录中的内部存储器。

我的结果:

boolean result = folder.mkdirs();

不是真的。所以没有文件夹打开,我也尝试过:

boolean result = folder.mkdir();

和我的Toasts说:

  1. 读写
  2. 23(API)
  3. 已安装(已安装)(
  4. 手机galaxy s5。 andorid version 6.0.1 Marshmallow。

    这是我的表现:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    
        package="com.example.thermie.test2">
    
    
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
        <application
    
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
        </application>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
    </manifest>
    

    希望它足够详细。 谢谢大家。

4 个答案:

答案 0 :(得分:0)

  

我认为我从Environment.getExternalStorageDirectory()获得的路径不是SD卡路径

正确。

getExternalFilesDirs()上使用Context方法。如果返回2 + File个对象,则第二个和后续对象将是可读取和写入的可移动存储上的位置,没有任何权限。

答案 1 :(得分:0)

你试过用过吗? Enviroment.getExternalStoragePublicDirectory()? 如上所述,您也可以使用     getExternalFilesDirs() 但是,在上下文中,这可能适用于某些设备。我指的是refer to here

答案 2 :(得分:0)

使用此

 public static File getCacheDirectory(Context context, boolean preferExternal) {
    File appCacheDir = null;
    String externalStorageState;
    try {
        externalStorageState = Environment.getExternalStorageState();
    } catch (NullPointerException e) {
        externalStorageState = "";
    }
    if (preferExternal && MEDIA_MOUNTED.equals(externalStorageState)) {
        appCacheDir = getSecondaryExternalCacheDir(context);
    }

    if (appCacheDir == null) {
        appCacheDir = getPrimaryExternalCacheDir(context);
    }
    return appCacheDir;
}

private static File getSecondaryExternalCacheDir(Context context) {
    File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
    File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
    if (!appCacheDir.exists()) {
        if (!appCacheDir.mkdirs()) {
            return null;
        }
    }
    return appCacheDir;
}

private static File getPrimaryExternalCacheDir(Context context) {
    File dataDir = new File(new File(context.getExternalFilesDir(null), "Android"), "data");
    File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
    if (!appCacheDir.exists()) {
        if (!appCacheDir.mkdirs()) {
            return null;
        }
    }
    return appCacheDir;
}

答案 3 :(得分:0)

好这是我的草率代码,它在我的本地存储中写了一个txt文件。 (xml文件相同)

package com.example.thermie.test2;


import android.Manifest;
import android.content.Context;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.R.attr.path;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    private String filename = "natiFile.txt";
    private String filepath = "/storage/extSdCard";
    File myExternalFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;


            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();


            File dir = Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM);
            final File file = new File(dir, "config.txt");

            String secStore = System.getenv("SECONDARY_STORAGE");
            File f_secs = new File(secStore);


            myExternalFile = new File(getExternalFilesDir(filepath), filename);

            String data = "gdsg";
            try {
                FileOutputStream fos = new FileOutputStream(myExternalFile);
                fos.write(data.getBytes());
                fos.close();
                Toast.makeText(MainActivity.this,
                        "great", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
            }



            File folder = new File(f_secs.getAbsolutePath() + "/TollCulator/");
            boolean testing = folder.mkdirs();
            if (testing){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(f_secs.getPath());
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}