【问题标题】:Creating a folder or file in External microSD card在外部 microSD 卡中创建文件夹或文件
【发布时间】:2017-03-30 11:15:31
【问题描述】:

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

我的目标是放入一张 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();

我的祝酒词说:

  1. 读写
  2. 23 (API)
  3. 挂载(SD挂载)

手机银河 s5。 andorid 版本 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>

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

【问题讨论】:

  • 您无法将文件写入 sd 卡。您只能在位于 android 文件夹中的 sd 卡上的 app 目录中写入文件
  • I think the Path that i get from: Environment.getExternalStorageDirectory() is not The SD Card Path. 。确实。功能名称清楚地表明,这不是 SD 卡,而是外部存储。
  • 但是您应该能够在您现在使用的路径中创建文件。所以你做错了什么。我认为您使用的是 Android 6 或更高版本并且忘记在运行时询问用户权限。

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


【解决方案1】:

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

正确。

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

【讨论】:

    【解决方案2】:

    您是否尝试过使用 Enviroment.getExternalStoragePublicDirectory()? 如上所述,您还可以使用 getExternalFilesDirs() 但是,根据上下文,这现在可能适用于某些设备。 refer to here 我指的是。

    【讨论】:

    • 使用 Enviroment.getExternalStoragePublicDirectory() 我必须输入一些文件夹,例如图片,所以我创建了一个图片文件夹但没有结果。我认为 Vivek Mishra 可能是对的,我正在检查它
    • Vivek Mishra 是对的。但由于您没有写入 SD 卡,因此评论无关紧要。
    • Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM) 无法正常工作
    • 是sd卡的路径吗?字符串 secStore = System.getenv("SECONDARY_STORAGE");文件 f_secs = 新文件(secStore);
    【解决方案3】:

    用这个

     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;
    }
    

    【讨论】:

      【解决方案4】:

      好的,这是我草率的代码,它正在我的本地存储中写入一个 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();
              }
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-04
        • 2012-09-20
        • 1970-01-01
        • 1970-01-01
        • 2018-05-18
        相关资源
        最近更新 更多