Sunday, June 3, 2012

Deleting files from the SDCard

As part of a recent project, I enabled users to export data from the database to the file system by clicking a button.  Users then wanted an easy way to delete the files that they created.   This little bit of code below does just that. It looks in the standard Android download directory (where I'm saving the files) for all the files that end in testfile.txt (I'm naming files {_id}_{date}_testfile.txt) and then deletes them one by one..



 Button clearJsonFiles = (Button) findViewById(R.id.clearJsonFiles); 
           clearJsonFiles.setOnClickListener(new OnClickListener()
           {
                public void onClick(View v)
                {
                     File path = Environment
                         .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                     File[] files = path.listFiles();
                     for (int i = 0; i < files.length; i++)
                     {
                          try {
                               Log.d(TAG, "Found File:" + files[i].getCanonicalFile());
                               if (files[i].getCanonicalPath().contains("testfile.txt")) {
                                    Log.d(TAG, "Deleting File:" + files[i].getCanonicalFile());
                                    //deleteExternalStoragePublicFile(files[i].getCanonicalPath());
                                    files[i].delete();
                               }
                          } catch (IOException e) {
                               // TODO Auto-generated catch block
                               e.printStackTrace();
                          }
                     }
                }
           });  

No comments:

Post a Comment