0

I have searched everywhere for the answer to my problem and i did found a large amount of answer which should have solved my it but yet i can't solved it.

My Goal is to put a SD card with 128GB and to write files into it (csv or text). I'm trying to open a file or a folder in my microSD card but it do not create it. also the file is not created. I think the Path that i get from:

Environment.getExternalStorageDirectory()

is not The SD Card Path.

here is my java code :

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

    }
}

My dir is : /storage/emulated/0/myDirectory Which is not in my SD card , it's the internal memory in an directory without any access.

my results of :

boolean result = folder.mkdirs();

is not true. so no folder opens , i also tried :

boolean result = folder.mkdir();

and my Toasts says:

  1. Read and Write
  2. 23 (API)
  3. mounted (sd mounted)

Phone galaxy s5. andorid version 6.0.1 Marshmallow.

Here is my manifeset :

<?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>

Hope it is detail enough. Thanks you all.

ankuranurag2
  • 2,300
  • 15
  • 30
  • you can't write files to sd card. You can only write files inside your app directory on sd card situated in android folder – Vivek Mishra Mar 30 '17 at 11:17
  • `I think the Path that i get from: Environment.getExternalStorageDirectory() is not The SD Card Path. `. Indeed. That is not SD card but external storage as the function name clearly indicates. – greenapps Mar 30 '17 at 12:59
  • But you should be able to create files in the path you use now. So you are doing something wrong. I think you use Android 6 or above and forgot to ask the user permission at runtime. – greenapps Mar 30 '17 at 13:01

4 Answers4

0

I think the Path that i get from Environment.getExternalStorageDirectory() is not The SD Card Path

Correct.

Use the getExternalFilesDirs() method on Context. If that returns 2+ File objects, the second and subsequent ones will be locations on removable storage that you can read and write, without any permissions.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

have you tried using the Enviroment.getExternalStoragePublicDirectory()? As was mentioned above, you can also use getExternalFilesDirs() on context, however, this might now work on some devices. refer to here for what I am referring to.

Community
  • 1
  • 1
Abeltensor
  • 132
  • 1
  • 10
  • using Enviroment.getExternalStoragePublicDirectory() i have to input some folder for example Pictures , So i created an Picture Folder but yet without results. I Think Vivek Mishra is might be right i'm checking it – Nati Barchilon Mar 30 '17 at 11:42
  • `Vivek Mishra` is right. But as you are not writing to SD card the comment is irrelevant. – greenapps Mar 30 '17 at 13:03
  • Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM) is not working as well – Nati Barchilon Mar 30 '17 at 14:04
  • is the path to the sd card ? String secStore = System.getenv("SECONDARY_STORAGE"); File f_secs = new File(secStore); – Nati Barchilon Mar 30 '17 at 15:43
0

Use this one

 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;
}
Pratik
  • 452
  • 4
  • 17
0

Ok This is my sloppy code and it's writing a txt file in my local storage. (xml file staied the same)

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

    }
}