当前位置: 移动技术网 > IT编程>移动开发>Android > Android开发之简单文件管理器实现方法

Android开发之简单文件管理器实现方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

帅哥的鸡图片,自驾游论坛,行尸走肉第七季11集

本文实例讲述了android开发之简单文件管理器实现方法。分享给大家供大家参考,具体如下:

这里运用java i/o、listactivity、dialog、bitmap等实现简单文件管理器,可以查看目录文件,修改文件名,删除文件,打开文件。比较简单,直接看代码:

先看布局文件:

layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<listview
 android:id="@android:id/list"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 />
</linearlayout>

文件列表布局:

layout/file.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="horizontal"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<imageview
 android:id="@+id/imageview"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
/>
<textview
 android:id="@+id/textview"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textsize="14sp">
</textview>
</linearlayout>

修改文件名对话框布局文件:

layout/rename_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 <edittext
  android:id="@+id/edittext"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
 />
</linearlayout>

主activity:

public class mainactivity extends listactivity {
 private static final string root_path = "/";
 //存储文件名称
 private arraylist<string> names = null;
 //存储文件路径
 private arraylist<string> paths = null;
 private view view;
 private edittext edittext;
 /** called when the activity is first created. */
 @override
 public void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.main);
  //显示文件列表
  showfiledir(root_path);
 }
 private void showfiledir(string path){
  names = new arraylist<string>();
  paths = new arraylist<string>();
  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<string> names = null;
 //存储文件路径
 private arraylist<string> paths = null;
 //参数初始化
 public myadapter(context context,arraylist<string> na,arraylist<string> 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"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.test.filemanager"
  android:versioncode="1"
  android:versionname="1.0">
 <uses-sdk android:minsdkversion="10" />
 <strong> <uses-permission android:name="android.permission.mount_unmount_filesystems"/>
 <uses-permission android:name="android.permission.write_external_storage"/></strong>
 <application android:icon="@drawable/icon" android:label="@string/app_name">
  <activity android:name=".mainactivity"
     android:label="@string/app_name">
   <intent-filter>
    <action android:name="android.intent.action.main" />
    <category android:name="android.intent.category.launcher" />
   </intent-filter>
  </activity>
 </application>
</manifest>

运行结果如下:

查看目录文件

文件重命名:

删除文件:

打开文件:

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网