How to Create Directory Automatically on Sd Card

How to create directory automatically on SD card

If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:

// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);

Note: It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.

UPDATE: Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:

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

How can I create a new directory on the SD card programmatically?

To create a directory you can use the following code:

File dir = new File("path/to/your/directory");
try{
if(dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory is not created");
}
}catch(Exception e){
e.printStackTrace();
}

To delete an empty directory, you can use this code:

boolean success = (new File("your/directory/name")).delete();
if (!success) {
System.out.println("Deletion failed!");
}

To delete a non-empty directory, you can use this code:

public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}

return dir.delete();
}

Maybe you also need this permission:

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

This answer is also a good resource:

How to create directory automatically on SD card

create a folder on an SD card

I just modified your code, here is the full code

public class Jobselection extends AppCompatActivity
implements View.OnClickListener {
private static final int REQUEST_CODE = 200 ;
Button createButton;
EditText photogname;
EditText projnum;
EditText phase;
DatePicker datePicker;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jobselection);
createButton = (Button) findViewById(R.id.createButton);
createButton.setOnClickListener(this);
photogname = (EditText) findViewById(R.id.editText);//added just to clear error
projnum = (EditText) findViewById(R.id.editText);//added just to clear erro
phase = (EditText) findViewById(R.id.editText);// added just to clear error
datePicker = (DatePicker) findViewById(R.id.datePicker);

}

public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year = datePicker.getYear();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
return calendar.getTime();
}

@RequiresApi(api = Build.VERSION_CODES.M)
public void onClick(View createButton) {
String date = getDateFromDatePicker(datePicker).toString();
String photog = "FinalTest";//photogname.getText().toString();just to clear error

String proj = projnum.getText().toString() + "." + phase.getText().toString();
String state;
state = Environment.getExternalStorageState();

if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v("Permisson", "Permission is granted");
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
}
}
if (Environment.MEDIA_MOUNTED.equals(state)) {
File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
boolean isDirectoryCreated = appDirectory.exists();
if (!isDirectoryCreated) {
isDirectoryCreated = appDirectory.mkdirs();
}
if (isDirectoryCreated) {
Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
} else
Log.d("error", "dir.already exists");
}
}
}
Intent launchUnitLoc = new Intent(this, UnitLocation.class);
startActivity(launchUnitLoc);

and your Manifest file should be like:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="[your package name]">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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">
<activity android:name=".Jobselection">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

how to create a folder in android External Storage Directory?

Do it like this :

String folder_main = "NewFolder";

File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}

If you wanna create another folder into that :

File f1 = new File(Environment.getExternalStorageDirectory() + "/" + folder_main, "product1");
if (!f1.exists()) {
f1.mkdirs();
}

Creating a directory in /sdcard fails

There are three things to consider here:

  1. Don't assume that the sd card is mounted at /sdcard (May be true in the default case, but better not to hard code.). You can get the location of sdcard by querying the system:

    Environment.getExternalStorageDirectory();
  2. You have to inform Android that your application needs to write to external storage by adding a uses-permission entry in the AndroidManifest.xml file:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  3. If this directory already exists, then mkdir is going to return false. So check for the existence of the directory, and then try creating it if it does not exist.
    In your component, use something like:

    File folder = new File(Environment.getExternalStorageDirectory() + "/map");
    boolean success = true;
    if (!folder.exists()) {
    success = folder.mkdir();
    }
    if (success) {
    // Do something on success
    } else {
    // Do something else on failure
    }

How to create Application specific directory on SDCard that should be deleted when the app is uninstalled

Your application doesn't get notified when it is being deleted, so you might be better off using the application's private directory, (from getFilesDir()). That directory is automatically deleted when the app is uninstalled.

Keep in mind that if you are on SDK 2.2+, you can allow your users the option of moving the entire application to the SD card, so you won't have to worry about the size of this directory.



Related Topics



Leave a reply



Submit