本文執行個體講述了Android開發之簡單檔案管理器實作方法。分享給大家供大家參考,具體如下:
這裡運用Java I/O、ListActivity、Dialog、Bitmap等實作簡單檔案管理器,可以檢視目錄檔案,修改檔案名,删除檔案,打開檔案。比較簡單,直接看代碼:
先看布局檔案:
layout/main.xml<?xml version="1.0" encoding="utf-8"?>
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
檔案清單布局:
layout/file.xml<?xml version="1.0" encoding="utf-8"?>
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp">
修改檔案名對話框布局檔案:
layout/rename_dialog.xml<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
主Activity:public class MainActivity extends ListActivity {
private static final String ROOT_PATH = "/";
//存儲檔案名稱
private ArrayList names = null;
//存儲檔案路徑
private ArrayList paths = null;
private View view;
private EditText editText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//顯示檔案清單
showFileDir(ROOT_PATH);
}
private void showFileDir(String path){
names = new ArrayList();
paths = new ArrayList();
File file = new File(path);
File[] files = file.listFiles();
//如果目前目錄不是根目錄
if (!ROOT_PATH.equals(path)){
names.add("@1");
paths.add(ROOT_PATH);
names.add("@2");
paths.add(file.getParent());
}
//添加所有檔案
for (File f : files){
names.add(f.getName());
paths.add(f.getPath());
}
this.setListAdapter(new MyAdapter(this,names, paths));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String path = paths.get(position);
File file = new File(path);
// 檔案存在并可讀
if (file.exists() && file.canRead()){
if (file.isDirectory()){
//顯示子目錄及檔案
showFileDir(path);
}
else{
//處理檔案
fileHandle(file);
}
}
//沒有權限
else{
Resources res = getResources();
new AlertDialog.Builder(this).setTitle("Message")
.setMessage(res.getString(R.string.no_permission))
.setPositiveButton("OK",new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
super.onListItemClick(l, v, position, id);
}
//對檔案進行增删改
private void fileHandle(final File file){
OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 打開檔案
if (which == 0){
openFile(file);
}
//修改檔案名
else if(which == 1){
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
view = factory.inflate(R.layout.rename_dialog, null);
editText = (EditText)view.findViewById(R.id.editText);
editText.setText(file.getName());
OnClickListener listener2 = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String modifyName = editText.getText().toString();
final String fpath = file.getParentFile().getPath();
final File newFile = new File(fpath + "/" + modifyName);
if (newFile.exists()){
//排除沒有修改情況
if (!modifyName.equals(file.getName())){
new AlertDialog.Builder(MainActivity.this)
.setTitle("注意!")
.setMessage("檔案名已存在,是否覆寫?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (file.renameTo(newFile)){
showFileDir(fpath);
displayToast("重命名成功!");
}
else{
displayToast("重命名失敗!");
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
}
else{
if (file.renameTo(newFile)){
showFileDir(fpath);
displayToast("重命名成功!");
}
else{
displayToast("重命名失敗!");
}
}
}
};
AlertDialog renameDialog = new AlertDialog.Builder(MainActivity.this).create();
renameDialog.setView(view);
renameDialog.setButton("确定", listener2);
renameDialog.setButton2("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
renameDialog.show();
}
//删除檔案
else{
new AlertDialog.Builder(MainActivity.this)
.setTitle("注意!")
.setMessage("确定要删除此檔案嗎?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(file.delete()){
//更新檔案清單
showFileDir(file.getParent());
displayToast("删除成功!");
}
else{
displayToast("删除失敗!");
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
};
//選擇檔案時,彈出增删該操作選項對話框
String[] menu = {"打開檔案","重命名","删除檔案"};
new AlertDialog.Builder(MainActivity.this)
.setTitle("請選擇要進行的操作!")
.setItems(menu, listener)
.setPositiveButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
//打開檔案
private void openFile(File file){
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
String type = getMIMEType(file);
intent.setDataAndType(Uri.fromFile(file), type);
startActivity(intent);
}
//擷取檔案mimetype
private String getMIMEType(File file){
String type = "";
String name = file.getName();
//檔案擴充名
String end = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();
if (end.equals("m4a") || end.equals("mp3") || end.equals("wav")){
type = "audio";
}
else if(end.equals("mp4") || end.equals("3gp")) {
type = "video";
}
else if (end.equals("jpg") || end.equals("png") || end.equals("jpeg") || end.equals("bmp") || end.equals("gif")){
type = "image";
}
else {
//如果無法直接打開,跳出清單由使用者選擇
type = "*";
}
type += "/*";
return type;
}
private void displayToast(String message){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
自定義擴充卡:public class MyAdapter extends BaseAdapter{
private LayoutInflater inflater;
private Bitmap directory,file;
//存儲檔案名稱
private ArrayList names = null;
//存儲檔案路徑
private ArrayList paths = null;
//參數初始化
public MyAdapter(Context context,ArrayList na,ArrayList pa){
names = na;
paths = pa;
directory = BitmapFactory.decodeResource(context.getResources(),R.drawable.d);
file = BitmapFactory.decodeResource(context.getResources(),R.drawable.f);
//縮小圖檔
directory = small(directory,0.16f);
file = small(file,0.1f);
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return names.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return names.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (null == convertView){
convertView = inflater.inflate(R.layout.file, null);
holder = new ViewHolder();
holder.text = (TextView)convertView.findViewById(R.id.textView);
holder.image = (ImageView)convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
}
else {
holder = (ViewHolder)convertView.getTag();
}
File f = new File(paths.get(position).toString());
if (names.get(position).equals("@1")){
holder.text.setText("/");
holder.image.setImageBitmap(directory);
}
else if (names.get(position).equals("@2")){
holder.text.setText("..");
holder.image.setImageBitmap(directory);
}
else{
holder.text.setText(f.getName());
if (f.isDirectory()){
holder.image.setImageBitmap(directory);
}
else if (f.isFile()){
holder.image.setImageBitmap(file);
}
else{
System.out.println(f.getName());
}
}
return convertView;
}
private class ViewHolder{
private TextView text;
private ImageView image;
}
private Bitmap small(Bitmap map,float num){
Matrix matrix = new Matrix();
matrix.postScale(num, num);
return Bitmap.createBitmap(map,0,0,map.getWidth(),map.getHeight(),matrix,true);
}
}
因為要對檔案進行操作,是以在描述檔案中授權:<?xml version="1.0" encoding="utf-8"?>
package="com.test.filemanager"
android:versionCode="1"
android:versionName="1.0">
android:label="@string/app_name">
運作結果如下:
檢視目錄檔案

檔案重命名:
删除檔案:
打開檔案:
希望本文所述對大家Android程式設計有所幫助。
更多Android開發之簡單檔案管理器實作方法相關文章請關注PHP中文網!
本文原創釋出php中文網,轉載請注明出處,感謝您的尊重!