如何对SD卡中的音频文件进行重命名/删除操作

时间:2013-12-17 07:20:53

标签: android audio

我正在尝试删除和重命名Sd卡中的音频文件,所以这是我的代码,用于显示SD卡中的音频文件列表。

// Use the current directory as title
    path = "/sdcard/";
    if (getIntent().hasExtra("path")) {
        path = getIntent().getStringExtra("path");
    }
    setTitle(path);

    // Read all files sorted into the values-array
    values = new ArrayList();
    File dir = new File(path);
    if (!dir.canRead()) {
        setTitle(getTitle() + " (inaccessible)");
    }
    final String[] list = dir.list();
    if (list != null) {
        for (String file : list) {
            if (file.contains(".3gp")) {
                values.add(file);
            }
        }
    }
    Collections.sort(values);
    // Put the data into the list
    adapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_2, android.R.id.text1, values);
    setListAdapter(adapter);

这里我可以显示所有音乐文件,但如果我尝试重命名或删除操作,那么它不会影响到SD卡中的文件,建议我一些解决方案PLZ 要删除和重命名的代码

case CONTEXT_MENU_DELETE:

Toast.makeText(
                this,
                "You selected item " + context_menu_number
                        + " from the context menu", Toast.LENGTH_SHORT)
                .show();
        Toast.makeText(
                this,
                "You removed item " + number_of_item_in_listview
                        + " from the list", Toast.LENGTH_SHORT).show();
        values.remove(number_of_item_in_listview);
        // myadapter.notifyDataSetChanged(); //if this does not work,
        // reinitialize the adapter:
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                values);
        myList.setAdapter(adapter);
        File f = new File(path + filename);
        if (f != null && f.exists()) {
            // delete it
            f.delete();
        }
        return (true);

2 个答案:

答案 0 :(得分:0)

尝试以下代码从SD卡中删除文件。

File file = new File(FilePath);
boolean deleted = file.delete();

其中FilePath是您要删除的文件的路径 - 例如:

/sdcard/YourCustomDirectory/YourFile.mp3

同时给予许可

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<{1>}文件中的

答案 1 :(得分:0)

首先在xml ..

中添加在外部存储上写入的权限
   String newName ="new Name";
   File oldFile = new File(Environment.getExternalStorageDirectory()+songName);

   File latestname = new File(Enviornment.get+ newName + ".mp3");
   boolean  success = oldFile .renameTo(latestname );