Hi all……
This is a simple example to create and delete a directory in ANDROID.
Here the directly is created in the SDCARD. So first create an SDCARD and start the emulator with the SDCARD.
Let’s look at the program.
Use can use this program to create or delete a file in ANDROID also.
package pack.coderzheaven; import java.io.File; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class CreateDeleteDIR_Example extends Activity { Button b; TextView t; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); t = (TextView)findViewById(R.id.tv); b= (Button) findViewById(R.id.Button01); File dir = new File("/sdcard/new_dir"); try{ if(dir.mkdir()) { System.out.println("Directory created"); t.setText("Directory created"); } else { System.out.println("Directory is not created"); t.setText("Directory is not created"); } }catch(Exception e){ e.printStackTrace(); } b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { File del = new File("/sdcard/new_dir"); boolean success = del.delete(); if (!success) { System.out.println("Deletion of directory failed!"); } } }); /* IF THE DIRECTORY IS NOT EMPTY . USE THIS FUNCTION */ public static boolean deleteNon_EmptyDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i<children.length; i++) { boolean success = deleteNon_EmptyDir(new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/tv" /> <Button android:text="Delete Directory" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> </LinearLayout>
Now go to File-explorer in the window menu->show View and see the result.
After directory creation.
After directory deletion.
Hi,
thx for that guide, but this single codeline is hard to read.