2016-02-08 224 views
0

我有一個內容菜單,在幾秒鐘內按下該項目時,彈出一個重命名和刪除菜單。但我不知道如何獲得一個文件的正確目錄。這裏是我的代碼:如何從存儲中刪除文件

@Override 
public boolean onContextItemSelected(MenuItem item) { 
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); 
    switch(item.getItemId()) { 
     case R.id.rename: 
      // edit stuff here 
      return true; 
     case R.id.delete: 

      File dir = new File(Environment.getExternalStorageDirectory()+"/Music/MusicPlayer"); 
      if (dir.isDirectory()) 
      { 
       String[] children = dir.list(); 
       for (int i = 0; i < children.length; i++) 
       { 
        new File(dir, children[i]).delete(); 
       } 
      } 

      // remove stuff here 
      return true; 
     default: 
      return super.onContextItemSelected(item); 
    } 
} 
+0

這是如何與Android的工作室? – Sufian

+0

'但我不知道如何獲得一個文件的正確目錄.'你沒有說明你是如何選擇文件。它在'ListView'中?可以選擇多個文件嗎? – Sufian

+0

它是在listview中,我不能選擇多個文件。 –

回答

0

而是使用的String [] =兒童dir.list()嘗試使用:以下功能

File dir = new File(PATH); 
File[] children = dir.listFiles(); 
for(int i = 0; i < children.length; i++) { 
    children[i].delete(); 
} 
0

使用從文件夾中刪除文件,只需通過在文件夾路徑perameter像

File fDir = new File(PERENT_PATH); 
DeleteRecursive(fDir); 
// where PERENT_PATH = Environment.getExternalStorageDirectory()+"/folderName" 

public static void DeleteRecursive(File fileOrDirectory) { 
     if (fileOrDirectory.isDirectory()) 
      for (File child : fileOrDirectory.listFiles()) 
       DeleteRecursive(child); 

     if (fileOrDirectory.exists()) { 
      boolean b = fileOrDirectory.delete(); 
      if (b) { 
       Log.e("delete dir", "delete dir"); 
      } else { 
       Log.e("not delete dir", "not delete dir"); 
      } 
     } 
    } 
0

請CHEC k下面的代碼

@Override 
    public boolean onContextItemSelected(MenuItem item) { 
     AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); 
     switch(item.getItemId()) { 
    ......... 
    case R.id.delete: 
     deleteDirectory(Environment.getExternalStorageDirectory()+"/Music/MusicPlayer"); 
     ......... 

    } 
    } 


static public boolean deleteDirectory(File path) { 
    if(path.exists()) { 
     File[] files = path.listFiles(); 
     for(int i=0; i<files.length; i++) { 
     if(files[i].isDirectory()) { 
      deleteDirectory(files[i]); 
     } 
     else { 
      files[i].delete(); 
     } 
     } 
    } 
    return(path.delete()); 
    } 
5

使用下面的util函數來刪除文件或目錄。

public static boolean delete(File path) { 
    boolean result = true; 
    if (path.exists()) { 
     if (path.isDirectory()) { 
      for (File child : path.listFiles()) { 
       result &= delete(child); 
      } 
      result &= path.delete(); // Delete empty directory. 
     } else if (path.isFile()) { 
      result &= path.delete(); 
     } 
     return result; 
    } else { 
     return false; 
    } 
} 

用法:

File dir = new File(Environment.getExternalStorageDirectory()+"/Music/MusicPlayer"); 
delete(dir);   
相關問題