Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 以编程方式清除所有SD卡文件_Java_Android_File_Android Asynctask_Android Sdcard - Fatal编程技术网

Java 以编程方式清除所有SD卡文件

Java 以编程方式清除所有SD卡文件,java,android,file,android-asynctask,android-sdcard,Java,Android,File,Android Asynctask,Android Sdcard,我正在尝试清除外部SD卡中存在的所有文件 我没有得到我的代码不工作的地方 这些是我的档案 activity-main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"

我正在尝试清除外部SD卡中存在的所有文件

我没有得到我的代码不工作的地方

这些是我的档案

activity-main.xml

    <?xml version="1.0" encoding="utf-8"?>

   <LinearLayout android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"
     xmlns:android="http://schemas.android.com/apk/res/android">

    <Button android:id="@+id/wipe_button" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
         android:text="Wipe the SD card." />

    <TextView android:id="@+id/path" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" />

    <TextView android:id="@+id/file" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" />

</LinearLayout>

在这里,我修改了WipeSDActivity.java类。请检查并让我知道。希望对您有所帮助。谢谢

import java.io.File;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class WipeSDActivity extends Activity {

      private static ProgressDialog progressBar;
      private static int progressBarStatus = 0;
      private static Handler progressBarHandler = new Handler();      
      public Button btnwipe_sd;
      private int fileCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sd_card);

    btnwipe_sd = (Button)findViewById(R.id.wipe_button);
    btnwipe_sd.setOnClickListener(new OnClickListener()
    {
          public void onClick(final View view)
          {

              new AlertDialog.Builder(WipeSDActivity.this).setCancelable(true)
              .setMessage("This will attempt to wipe all directories and files on your SD card.")
              .setPositiveButton("WIPE", new DialogInterface.OnClickListener()
              {
                public void onClick(DialogInterface dialog, int which)
                {
                  dialog.dismiss();
                  FormatSDCard(view);
                }
              }).setNegativeButton("NO!", new DialogInterface.OnClickListener()
              {
                public void onClick(DialogInterface dialog, int which)
                {
                  dialog.dismiss();
                }
              }).show();
          }
        });
    }


    public void FormatSDCard(View v){
        progressBar = new ProgressDialog(v.getContext());
        progressBar.setCancelable(false);
        progressBar.setMessage("File deleting ...");
        progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressBar.setProgress(0);
        progressBar.setMax(100);
        progressBar.show();

        new Thread(new Runnable() {
            public void run() {
                while (progressBarStatus < 100) {
                    //fileCount = 0;
                    // process some tasks
                    progressBarStatus = wipingSdcard();
                    // your computer is too fast, sleep 1 second
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // Update the progress bar
                    progressBarHandler.post(new Runnable() {
                        public void run() {
                            progressBar.setProgress(progressBarStatus);
                        }
                    });
                }

                // ok, file is deleted,
                if (progressBarStatus >= 100) {

                    // sleep 2 seconds, so that you can see the 100%
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // close the progress bar dialog
                    progressBar.dismiss();
                }
            }
        }).start();     
    }


    public int wipingSdcard() {
    File deleteMatchingFile = new File(Environment
            .getExternalStorageDirectory().toString());
    try {
        File[] filenames = deleteMatchingFile.listFiles();
        if (filenames != null && filenames.length > 0) {
            for (File tempFile : filenames) {
                if (tempFile.isDirectory()) {
                    wipeDirectory(tempFile.toString());
                    tempFile.delete();
                } else {
                    tempFile.delete();
                }
                fileCount++;
                progressBarStatus = fileCount;

                    progressBarHandler.post(new Runnable() {
                        public void run() {
                            progressBar.setProgress(progressBarStatus);
                        }
                    });
            }
        } else {
            deleteMatchingFile.delete();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
        return fileCount;
    }

    private void wipeDirectory(String name) {
    File directoryFile = new File(name);
    File[] filenames = directoryFile.listFiles();
    if (filenames != null && filenames.length > 0) {
        for (File tempFile : filenames) {
            if (tempFile.isDirectory()) {
                wipeDirectory(tempFile.toString());
                tempFile.delete();
            } else {
                tempFile.delete();
            }
        }
    } else {
        directoryFile.delete();
    }
    }
}
导入java.io.File;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.app.ProgressDialog;
导入android.content.DialogInterface;
导入android.os.Bundle;
导入android.os.Environment;
导入android.os.Handler;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
公共类WipesActivity扩展了活动{
私有静态ProgressDialog progressBar;
私有静态int progressBarStatus=0;
私有静态处理程序progressBarHandler=新处理程序();
公共按钮btnwipe_sd;
私有int fileCount=0;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.sd_卡);
btnwipe_sd=(按钮)findViewById(R.id.wipe_按钮);
btnwipe_sd.setOnClickListener(新的OnClickListener()
{
公共void onClick(最终视图)
{
新建AlertDialog.Builder(wipesActivity.this).setCancelable(true)
.setMessage(“这将尝试擦除SD卡上的所有目录和文件。”)
.setPositiveButton(“擦除”,新的DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
dialog.dismise();
格式卡(视图);
}
}).setNegativeButton(“否!”,新建DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
dialog.dismise();
}
}).show();
}
});
}
公共作废格式卡(视图五){
progressBar=newprogressdialog(v.getContext());
progressBar.setCancelable(假);
setMessage(“文件删除…”);
progressBar.setProgressStyle(ProgressDialog.STYLE_水平);
progressBar.setProgress(0);
设置最大进度条(100);
progressBar.show();
新线程(newrunnable()){
公开募捐{
而(状态<100){
//fileCount=0;
//处理一些任务
progressBarStatus=wipingSdcard();
//您的计算机速度太快,请睡眠1秒
试一试{
睡眠(1000);
}捕捉(中断异常e){
e、 printStackTrace();
}
//更新进度条
progressBarHandler.post(新的Runnable(){
公开募捐{
progressBar.setProgress(progressBar状态);
}
});
}
//好的,文件被删除了,
如果(progressBarStatus>=100){
//睡2秒钟,这样你就可以看到100%
试一试{
《睡眠》(2000年);
}捕捉(中断异常e){
e、 printStackTrace();
}
//关闭进度条对话框
progressBar.disclose();
}
}
}).start();
}
公共int wipingSdcard(){
File deleteMatchingFile=新文件(环境)
.getExternalStorageDirectory().toString());
试一试{
File[]filename=deleteMatchingFile.listFiles();
if(filenames!=null&&filenames.length>0){
对于(文件tempFile:filenames){
if(tempFile.isDirectory()){
wipeDirectory(tempFile.toString());
tempFile.delete();
}否则{
tempFile.delete();
}
fileCount++;
progressBarStatus=文件计数;
progressBarHandler.post(新的Runnable(){
公开募捐{
progressBar.setProgress(progressBar状态);
}
});
}
}否则{
deleteMatchingFile.delete();
}
}捕获(例外e){
e、 printStackTrace();
}
返回文件计数;
}
私有目录(字符串名称){
文件目录File=新文件(名称);
File[]filename=directoryFile.listFiles();
if(filenames!=null&&filenames.length>0){
对于(文件tempFile:filenames){
if(tempFile.isDirectory()){
wipeDirectory(tempFile.toString());
tempFile.delete();
}否则{
tempFile.delete();
}
}
}否则{
directoryFile.delete();
}
}
}
此外,如果您使用的是>1.6 SDK,则必须授予权限

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


在AndroidManifest.xml文件中,请尝试使用这些代码。嘿,杰巴,实际上我在执行任务时检查了这些代码。它工作,但我需要在一个简单的任务方式做。检查这个应用程序。我需要这样做。请帮助我。你也可以使用FileUtils.deleteDirectory:Hey Jeba,这不是格式化我的Emulator Sd卡。帮帮我。@Jeba,如果你得到结果,请告诉我。@NayanRath,很抱歉反应太晚,我修改了源代码。请再次检查并告诉我。这对我来说很好。Thanks@NayanRath,请告诉我它是否工作。它的工作原理
02-08 16:47:13.460: E/AndroidRuntime(270): java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.example.wipe_sd/com.example.wipe_sd.WipeSDActivity}: java.lang.NullPointerException
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.os.Looper.loop(Looper.java:123)
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.app.ActivityThread.main(ActivityThread.java:4627)
02-08 16:47:13.460: E/AndroidRuntime(270):  at java.lang.reflect.Method.invokeNative(Native Method)
02-08 16:47:13.460: E/AndroidRuntime(270):  at java.lang.reflect.Method.invoke(Method.java:521)
02-08 16:47:13.460: E/AndroidRuntime(270):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-08 16:47:13.460: E/AndroidRuntime(270):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-08 16:47:13.460: E/AndroidRuntime(270):  at dalvik.system.NativeStart.main(Native Method)
02-08 16:47:13.460: E/AndroidRuntime(270): Caused by: java.lang.NullPointerException
02-08 16:47:13.460: E/AndroidRuntime(270):  at com.example.wipe_sd.WipeSDActivity$MyAsyncTask.onPreExecute(WipeSDActivity.java:204)
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.os.AsyncTask.execute(AsyncTask.java:391)
02-08 16:47:13.460: E/AndroidRuntime(270):  at com.example.wipe_sd.WipeSDActivity.onCreate(WipeSDActivity.java:44)
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-08 16:47:13.460: E/AndroidRuntime(270):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-08 16:47:13.460: E/AndroidRuntime(270):  ... 11 more
import java.io.File;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class WipeSDActivity extends Activity {

      private static ProgressDialog progressBar;
      private static int progressBarStatus = 0;
      private static Handler progressBarHandler = new Handler();      
      public Button btnwipe_sd;
      private int fileCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sd_card);

    btnwipe_sd = (Button)findViewById(R.id.wipe_button);
    btnwipe_sd.setOnClickListener(new OnClickListener()
    {
          public void onClick(final View view)
          {

              new AlertDialog.Builder(WipeSDActivity.this).setCancelable(true)
              .setMessage("This will attempt to wipe all directories and files on your SD card.")
              .setPositiveButton("WIPE", new DialogInterface.OnClickListener()
              {
                public void onClick(DialogInterface dialog, int which)
                {
                  dialog.dismiss();
                  FormatSDCard(view);
                }
              }).setNegativeButton("NO!", new DialogInterface.OnClickListener()
              {
                public void onClick(DialogInterface dialog, int which)
                {
                  dialog.dismiss();
                }
              }).show();
          }
        });
    }


    public void FormatSDCard(View v){
        progressBar = new ProgressDialog(v.getContext());
        progressBar.setCancelable(false);
        progressBar.setMessage("File deleting ...");
        progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressBar.setProgress(0);
        progressBar.setMax(100);
        progressBar.show();

        new Thread(new Runnable() {
            public void run() {
                while (progressBarStatus < 100) {
                    //fileCount = 0;
                    // process some tasks
                    progressBarStatus = wipingSdcard();
                    // your computer is too fast, sleep 1 second
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // Update the progress bar
                    progressBarHandler.post(new Runnable() {
                        public void run() {
                            progressBar.setProgress(progressBarStatus);
                        }
                    });
                }

                // ok, file is deleted,
                if (progressBarStatus >= 100) {

                    // sleep 2 seconds, so that you can see the 100%
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // close the progress bar dialog
                    progressBar.dismiss();
                }
            }
        }).start();     
    }


    public int wipingSdcard() {
    File deleteMatchingFile = new File(Environment
            .getExternalStorageDirectory().toString());
    try {
        File[] filenames = deleteMatchingFile.listFiles();
        if (filenames != null && filenames.length > 0) {
            for (File tempFile : filenames) {
                if (tempFile.isDirectory()) {
                    wipeDirectory(tempFile.toString());
                    tempFile.delete();
                } else {
                    tempFile.delete();
                }
                fileCount++;
                progressBarStatus = fileCount;

                    progressBarHandler.post(new Runnable() {
                        public void run() {
                            progressBar.setProgress(progressBarStatus);
                        }
                    });
            }
        } else {
            deleteMatchingFile.delete();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
        return fileCount;
    }

    private void wipeDirectory(String name) {
    File directoryFile = new File(name);
    File[] filenames = directoryFile.listFiles();
    if (filenames != null && filenames.length > 0) {
        for (File tempFile : filenames) {
            if (tempFile.isDirectory()) {
                wipeDirectory(tempFile.toString());
                tempFile.delete();
            } else {
                tempFile.delete();
            }
        }
    } else {
        directoryFile.delete();
    }
    }
}
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>