我想处理来自SD卡的所有歌曲(比如删除或重命名),所以我列出了列表视图中的所有音乐文件,但我不知道如何处理该列表,这是我到目前为止所尝试的: / p>
// Use the current directory as title
path = "/sdcard/AudioRecorder/";
if (getIntent().hasExtra("path")) {
path = getIntent().getStringExtra("path");
}
setTitle(path);
// Read all files sorted into the values-array
final List 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.startsWith(".")) {
values.add(file);
}
}
}
Collections.sort(values);
// Put the data into the list
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, android.R.id.text1, values);
setListAdapter(adapter);
myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
return onLongListItemClick(v, pos, id);
}
private boolean onLongListItemClick(View v, final int pos, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(ListFileActivity.this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
File file = new File(path+filename);
file.delete();
values.remove(pos);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
filename = (String) getListAdapter().getItem(position);
Toast.makeText(getApplicationContext(), filename, Toast.LENGTH_LONG).show();
}
在这里,我可以删除列表项,但文件不能在SD卡上删除 重命名让我不知道如何接近。
答案 0 :(得分:1)
要删除文件,请使用以下
File file = new File("absolute_path_of_filename");
// check if file is not a directory
if(!file.isDirectory()) {
// if not then delete it
file.delete();
}
重新命名使用file.renameTo("filename with path");