Create a new directory on external storage : Environment « Core Class « Android






Create a new directory on external storage

    

package app.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;

public class Test extends Activity {

    private static final String FILENAME = "data.txt";
    private static final String DNAME = "myfiles";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        setContentView(tv);
        
        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();
        }
        try {
            FileInputStream mInput = new FileInputStream(dataFile);
            byte[] data = new byte[128];
            mInput.read(data);
            mInput.close();
            
            String display = new String(data);
            tv.setText(display.trim());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        dataFile.delete();    
    }
}

   
    
    
    
  








Related examples in the same category

1.May crash when External-Media is not mounted.
2.is Storage Readable/Writable
3.Get External Storage Directory
4.Environment.MEDIA_MOUNTED, Environment.MEDIA_MOUNTED_READ_ONLY
5.Utility class used to deal with SD card cache.
6.return True if the external storage is available/writable.