1

I am trying to create a file in the external SD card storage. The file is not getting created. Interestingly, I have copied the create_file() from one of my otherprojects where it is working perfectly.

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); create_file(); } private void create_file() { String pathToExternalStorage = Environment.getExternalStorageDirectory() .toString(); File appDirectory = new File(pathToExternalStorage + "/" + "Accel"); appDirectory.mkdirs(); String fname = "Data.txt"; File f_data = new File(appDirectory, fname); try { if (!f_data.exists()) { f_data.createNewFile(); Toast.makeText(this, "File Created", Toast.LENGTH_SHORT).show(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 
3
  • 1
    Does it throw an error? What happens when you run it? Nothing? Commented Nov 13, 2013 at 14:30
  • 1
    Is the toast presented? Commented Nov 13, 2013 at 14:31
  • I should avoid converting from File to String. You can do: Final external = Environment.getExternalStorageDirectory(); File appDir = new File(external, "Accel"); File fData = new File(appDir, "Data.txt); Commented Nov 13, 2013 at 14:38

2 Answers 2

3

Firstly, I would check if proper permissions were added in your AndroidManifest.xml file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

What is more, I checked the docs and I guess instead of calling .toString():

String pathToExternalStorage = Environment.getExternalStorageDirectory().toString() 

you should rather use .getPath() method in there:

String pathToExternalStorage = Environment.getExternalStorageDirectory().getPath() 
Sign up to request clarification or add additional context in comments.

1 Comment

I did not add the permission. Thanks
1

You should add the following permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

in your manifest.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.