<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
String path = "/mnt/sdcard/mydata/mytext.txt"; File file = new File(path); file.delete();
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="33dp" android:text="Input File name and path" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="16dp" android:ems="20" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText1" android:layout_centerHorizontal="true" android:layout_marginTop="44dp" android:text="Delete" /> </RelativeLayout>
package com.myapp; import java.io.File; import java.io.IOException; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // editText1 File name final EditText txtFilename = (EditText) findViewById(R.id.editText1); // button1 final Button btn1 = (Button) findViewById(R.id.button1); // Perform action on click btn1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { /*** Delete file in SD Card ***/ try { String path = txtFilename.getText().toString(); File file = new File(path); if(file.exists()) { file.delete(); } file = null; Toast.makeText(MainActivity.this, "File Delete!", Toast.LENGTH_LONG).show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(MainActivity.this, "Failed! = " + e.getMessage() , Toast.LENGTH_LONG).show(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท