android文件管理器用法详解

很久没有写东西了,鉴于某某同学文件管理器不会,这里简单介绍一下,同时写一个demon,参考了网上别人写的代码,自己也学习学习,研究研究。

  首先所谓文件管理器,看起来就是一个列表,列表里面是文件夹或者文件,首先把布局写出来,我想在最上方的左边显示文件的路径,右边显示该路径下的文件个数,其实还是一个遍历文件,然后用列表显示出来的问题。下面是ListView,用来显示文件列表。下面是运行的效果图:

android文件管理器用法详解_第1张图片

主界面的布局文件如下:



  
    
    
    
  
  

  
    
    
  

首先在oncreate方法里面调用一个方法去获取布局文件里面的id:

@Override
   protected void onCreate (Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.file_manager);
     initView();
 }

initView之后添加apk的权限,777 表示可读可写可操作。

private void initView() {
    mListView = (ListView) findViewById(R.id.file_list);
    mPathView = (TextView) findViewById(R.id.path);
    mItemCount = (TextView) findViewById(R.id.item_count);
    mListView.setOnItemClickListener(this);
    String apkRoot = "chmod 777 " + getPackageCodePath(); 
    RootCommand(apkRoot);
    File folder = new File("/");
    initData(folder);
  } 

修改Root权限的方法:

public static boolean RootCommand (String command) {
    Process process = null;
    DataOutputStream os = null;
    try {
      process = Runtime.getRuntime().exec("su");
      os = new DataOutputStream(process.getOutputStream());
      os.writeBytes(command + "\n");
      os.writeBytes("exit\n");
      os.flush();
      process.waitFor();
    }
    catch (Exception e) {
      return false;
    }
    finally {
      try {
        if (os != null) {
          os.close();
        }
        process.destroy();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
    return true;
  }

完了之后我们要获取根目录下面的所有的数据,然后设置到我们的ListView中让它显示出来。

private void initData(File folder) {
    boolean isRoot = folder.getParent() == null; 
    mPathView.setText(folder.getAbsolutePath()); 
    ArrayList files = new ArrayList();  
    if (!isRoot) {
      files.add(folder.getParentFile()); 
    }
    File[] filterFiles = folder.listFiles(); 
    mItemCount.setText(filterFiles.length + "项"); 
    if (null != filterFiles && filterFiles.length > 0) {
      for (File file : filterFiles) {
        files.add(file);
      }
    }
    mFileAdpter = new FileListAdapter(this, files, isRoot); 
    mListView.setAdapter(mFileAdpter);
  }

首先是获取当前是否是根目录,然后把文件的路径设置给我们要显示的View。

然后用一个ArrayList来装我们目录下的所有的文件或者文件夹。

首先要把这个文件夹的父类装到我们的列表中去,然后把这个文件夹下的子文件都拿到,也装在列表中,然后调用Adapter显示出来。既然说到了Adapter, 那就看下Adapter吧。

private class FileListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList files;
    private boolean isRoot;
    private LayoutInflater mInflater;
    
    public FileListAdapter (Context context, ArrayList files, boolean isRoot) {
      this.context = context;
      this.files = files;
      this.isRoot = isRoot;
      mInflater = LayoutInflater.from(context);
    }
    
    @Override
    public int getCount () {
      return files.size();
    }

    @Override
    public Object getItem (int position) {
      return files.get(position);
    }

    @Override
    public long getItemId (int position) {
      return position;
    }
    
    @Override
    public View getView (int position, View convertView, ViewGroup parent) {
      ViewHolder viewHolder;
      if(convertView == null) {
        viewHolder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.file_list_item, null);
        convertView.setTag(viewHolder);
        viewHolder.title = (TextView) convertView.findViewById(R.id.file_title);
        viewHolder.type = (TextView) convertView.findViewById(R.id.file_type);
        viewHolder.data = (TextView) convertView.findViewById(R.id.file_date);
        viewHolder.size = (TextView) convertView.findViewById(R.id.file_size);
      } else {
        viewHolder = (ViewHolder) convertView.getTag();
      }
      
      File file = (File) getItem(position);
      if(position == 0 && !isRoot) {
        viewHolder.title.setText("返回上一级");
        viewHolder.data.setVisibility(View.GONE);
        viewHolder.size.setVisibility(View.GONE);
        viewHolder.type.setVisibility(View.GONE);
      } else {
        String fileName = file.getName();
        viewHolder.title.setText(fileName);
        if(file.isDirectory()) {
          viewHolder.size.setText("文件夹");
          viewHolder.size.setTextColor(Color.RED);
          viewHolder.type.setVisibility(View.GONE);
          viewHolder.data.setVisibility(View.GONE);
        } else {
          long fileSize = file.length();
          if(fileSize > 1024*1024) {
            float size = fileSize /(1024f*1024f);
            viewHolder.size.setText(new DecimalFormat("#.00").format(size) + "MB");
          } else if(fileSize >= 1024) {
            float size = fileSize/1024;
            viewHolder.size.setText(new DecimalFormat("#.00").format(size) + "KB");
          } else {
            viewHolder.size.setText(fileSize + "B");
          }
          int dot = fileName.indexOf('.');
          if(dot > -1 && dot < (fileName.length() -1)) {
            viewHolder.type.setText(fileName.substring(dot + 1) + "文件");
          }
          viewHolder.data.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm").format(file.lastModified()));
        }
      }
      return convertView;
    }
    
    class ViewHolder {
      private TextView title;
      private TextView type;
      private TextView data;
      private TextView size;
    }
  }

看下adapter的布局文件:



  
  
    
    
    
    
  

列表的Item项分2行显示,上面一行显示文件名

下面一行分别显示文件大小,文件类型,文件修改时间。

我们可以通过File file = (File) getItem(position);拿到Item项的文件,如果是在第一个并且不再根目录我们就把第一个也就是parentFile显示为:“返回上一级”,下一行的都隐藏掉。

如果不是第一个位置,可以拿到这个文件的一系列信息。

先把String fileName = file.getName();文件名拿到,显示出来。

如果这个文件是一个文件夹,就把文件的大小显示为“文件夹”,类型和修改时间隐藏掉。

如果不是一个文件夹, 可以拿到文件的长度long fileSize = file.length();

根据特定的长度显示文件的大小,B, KB, MB, GB等。

然后拿到文件的类型,通过最后一个“.”之后的字符串就是该文件的类型。

通过viewHolder.data.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm").format(file.lastModified())); 设置文件的最近修改时间。

然后可以设置每个Item项的点击事件,如下所示:

@Override
  public void onItemClick (AdapterView parent, View view, int position, long id) {
    File file = (File) mFileAdpter.getItem(position);
    if(!file.canRead()) {
      new AlertDialog.Builder(this).setTitle("提示").setMessage("权限不足").setPositiveButton(android.R.string.ok, new OnClickListener() {
        
        @Override
        public void onClick (DialogInterface dialog, int which) {
          
        }
      }).show();
    } else if(file.isDirectory()) {
      initData(file);
    } else {
      openFile(file);
    }
  }

如果这个文件不能读,就弹出对话框显示“权限不足”。

如果是一个文件夹,就在调用一次显示所有文件的方法:initData(file);把这个文件夹作为参数传递下去。

如果是一个文件,就可以调用打开文件的方法打开这个文件。

如何打开文件呢?

可以根据不同的文件的后缀名找到不同的文件类型:

可以用一个二维数组把一些常用的文件类型封装起来。如下:

private final String[][] MIME_MapTable = {
    // {后缀名, MIME类型}
    { ".3gp", "video/3gpp" }, 
    { ".apk", "application/vnd.android.package-archive" }, 
    { ".asf", "video/x-ms-asf" }, 
    { ".avi", "video/x-msvideo" },
    { ".bin", "application/octet-stream" }, 
    { ".bmp", "image/bmp" }, 
    { ".c", "text/plain" }, 
    { ".class", "application/octet-stream" },
    { ".conf", "text/plain" }, 
    { ".cpp", "text/plain" }, 
    { ".doc", "application/msword" },
    { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, 
    { ".xls", "application/vnd.ms-excel" },
    { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, 
    { ".exe", "application/octet-stream" },
    { ".gif", "image/gif" }, 
    { ".gtar", "application/x-gtar" }, 
    { ".gz", "application/x-gzip" }, 
    { ".h", "text/plain" }, 
    { ".htm", "text/html" },
    { ".html", "text/html" }, 
    { ".jar", "application/java-archive" }, 
    { ".java", "text/plain" }, 
    { ".jpeg", "image/jpeg" },
    { ".jpg", "image/jpeg" }, 
    { ".js", "application/x-javascript" }, 
    { ".log", "text/plain" }, 
    { ".m3u", "audio/x-mpegurl" },
    { ".m4a", "audio/mp4a-latm" }, 
    { ".m4b", "audio/mp4a-latm" }, 
    { ".m4p", "audio/mp4a-latm" }, 
    { ".m4u", "video/vnd.mpegurl" },
    { ".m4v", "video/x-m4v" }, 
    { ".mov", "video/quicktime" }, 
    { ".mp2", "audio/x-mpeg" }, 
    { ".mp3", "audio/x-mpeg" }, 
    { ".mp4", "video/mp4" },
    { ".mpc", "application/vnd.mpohun.certificate" }, 
    { ".mpe", "video/mpeg" }, 
    { ".mpeg", "video/mpeg" }, 
    { ".mpg", "video/mpeg" },
    { ".mpg4", "video/mp4" }, 
    { ".mpga", "audio/mpeg" }, 
    { ".msg", "application/vnd.ms-outlook" }, 
    { ".ogg", "audio/ogg" },
    { ".pdf", "application/pdf" }, 
    { ".png", "image/png" }, 
    { ".pps", "application/vnd.ms-powerpoint" },
    { ".ppt", "application/vnd.ms-powerpoint" }, 
    { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
    { ".prop", "text/plain" }, 
    { ".rc", "text/plain" }, 
    { ".rmvb", "audio/x-pn-realaudio" }, 
    { ".rtf", "application/rtf" },
    { ".sh", "text/plain" }, 
    { ".tar", "application/x-tar" }, 
    { ".tgz", "application/x-compressed" }, 
    { ".txt", "text/plain" },
    { ".wav", "audio/x-wav" }, 
    { ".wma", "audio/x-ms-wma" }, 
    { ".wmv", "audio/x-ms-wmv" }, 
    { ".wps", "application/vnd.ms-works" },
    { ".xml", "text/plain" }, 
    { ".z", "application/x-compress" }, 
    { ".zip", "application/x-zip-compressed" }, 
    { "", "*/*" } 
    };

分别对应的是后缀名和对应的文件类型。

我们可以根据文件的后缀名拿到文件的MIMEType类型:

private String getMIMEType(File file) {
    String type = "*/*";
    String fileName = file.getName();
    int dotIndex = fileName.indexOf('.');
    if(dotIndex < 0) {
      return type;
    }
    String end = fileName.substring(dotIndex, fileName.length()).toLowerCase();
    if(end == "") {
      return type;
    }
    for(int i=0; i 
 

先遍历后缀名,如果找到,就把对应的类型找到并返回。

拿到了类型,就可以打开这个文件。

用这个intent.setDataAndType(Uri.fromFile(file), type); 打开设置打开文件的类型。

如果type是*/*会弹出所有的可供选择的应用程序。

 到这里一个简易的文件管理器就成型了。

源代码:

package com.android.test;

import java.io.DataOutputStream;
import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FileManager extends Activity implements OnItemClickListener {
  
  private ListView mListView;
  private TextView mPathView;
  private FileListAdapter mFileAdpter;
  private TextView mItemCount;
  
  @Override
  protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.file_manager);
    initView();
  }
  
  private void initView() {
    mListView = (ListView) findViewById(R.id.file_list);
    mPathView = (TextView) findViewById(R.id.path);
    mItemCount = (TextView) findViewById(R.id.item_count);
    mListView.setOnItemClickListener(this);
    String apkRoot = "chmod 777 " + getPackageCodePath(); 
    RootCommand(apkRoot);
    File folder = new File("/");
    initData(folder);
  }
  
  public static boolean RootCommand (String command) {
    Process process = null;
    DataOutputStream os = null;
    try {
      process = Runtime.getRuntime().exec("su");
      os = new DataOutputStream(process.getOutputStream());
      os.writeBytes(command + "\n");
      os.writeBytes("exit\n");
      os.flush();
      process.waitFor();
    }
    catch (Exception e) {
      return false;
    }
    finally {
      try {
        if (os != null) {
          os.close();
        }
        process.destroy();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
    return true;
  }
  
  private void initData(File folder) {
    boolean isRoot = folder.getParent() == null; 
    mPathView.setText(folder.getAbsolutePath()); 
    ArrayList files = new ArrayList();  
    if (!isRoot) {
      files.add(folder.getParentFile()); 
    }
    File[] filterFiles = folder.listFiles(); 
    mItemCount.setText(filterFiles.length + "项"); 
    if (null != filterFiles && filterFiles.length > 0) {
      for (File file : filterFiles) {
        files.add(file);
      }
    }
    mFileAdpter = new FileListAdapter(this, files, isRoot); 
    mListView.setAdapter(mFileAdpter);
  }
  
  private class FileListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList files;
    private boolean isRoot;
    private LayoutInflater mInflater;
    
    public FileListAdapter (Context context, ArrayList files, boolean isRoot) {
      this.context = context;
      this.files = files;
      this.isRoot = isRoot;
      mInflater = LayoutInflater.from(context);
    }
    
    @Override
    public int getCount () {
      return files.size();
    }

    @Override
    public Object getItem (int position) {
      return files.get(position);
    }

    @Override
    public long getItemId (int position) {
      return position;
    }
    
    @Override
    public View getView (int position, View convertView, ViewGroup parent) {
      ViewHolder viewHolder;
      if(convertView == null) {
        viewHolder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.file_list_item, null);
        convertView.setTag(viewHolder);
        viewHolder.title = (TextView) convertView.findViewById(R.id.file_title);
        viewHolder.type = (TextView) convertView.findViewById(R.id.file_type);
        viewHolder.data = (TextView) convertView.findViewById(R.id.file_date);
        viewHolder.size = (TextView) convertView.findViewById(R.id.file_size);
      } else {
        viewHolder = (ViewHolder) convertView.getTag();
      }
      
      File file = (File) getItem(position);
      if(position == 0 && !isRoot) {
        viewHolder.title.setText("返回上一级");
        viewHolder.data.setVisibility(View.GONE);
        viewHolder.size.setVisibility(View.GONE);
        viewHolder.type.setVisibility(View.GONE);
      } else {
        String fileName = file.getName();
        viewHolder.title.setText(fileName);
        if(file.isDirectory()) {
          viewHolder.size.setText("文件夹");
          viewHolder.size.setTextColor(Color.RED);
          viewHolder.type.setVisibility(View.GONE);
          viewHolder.data.setVisibility(View.GONE);
        } else {
          long fileSize = file.length();
          if(fileSize > 1024*1024) {
            float size = fileSize /(1024f*1024f);
            viewHolder.size.setText(new DecimalFormat("#.00").format(size) + "MB");
          } else if(fileSize >= 1024) {
            float size = fileSize/1024;
            viewHolder.size.setText(new DecimalFormat("#.00").format(size) + "KB");
          } else {
            viewHolder.size.setText(fileSize + "B");
          }
          int dot = fileName.indexOf('.');
          if(dot > -1 && dot < (fileName.length() -1)) {
            viewHolder.type.setText(fileName.substring(dot + 1) + "文件");
          }
          viewHolder.data.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm").format(file.lastModified()));
        }
      }
      return convertView;
    }
    
    class ViewHolder {
      private TextView title;
      private TextView type;
      private TextView data;
      private TextView size;
    }
  }

  @Override
  public void onItemClick (AdapterView parent, View view, int position, long id) {
    File file = (File) mFileAdpter.getItem(position);
    if(!file.canRead()) {
      new AlertDialog.Builder(this).setTitle("提示").setMessage("权限不足").setPositiveButton(android.R.string.ok, new OnClickListener() {
        
        @Override
        public void onClick (DialogInterface dialog, int which) {
          
        }
      }).show();
    } else if(file.isDirectory()) {
      initData(file);
    } else {
      openFile(file);
    }
  }
  
  private void openFile(File file) {
    Intent intent = new Intent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    intent.setAction(Intent.ACTION_VIEW); 
    String type = getMIMEType(file); 
    intent.setDataAndType(Uri.fromFile(file), type); 
    try {
      startActivity(intent);
    }
    catch (Exception e) {
      Toast.makeText(this, "未知类型,不能打开", Toast.LENGTH_SHORT).show();
    }
  }
  
  private String getMIMEType(File file) {
    String type = "*/*";
    String fileName = file.getName();
    int dotIndex = fileName.indexOf('.');
    if(dotIndex < 0) {
      return type;
    }
    String end = fileName.substring(dotIndex, fileName.length()).toLowerCase();
    if(end == "") {
      return type;
    }
    for(int i=0; i 
 

最后补充一下,布局文件中的dimension是编译到jar包里面去了的,没有jar包的童鞋可以改成自己定义大小。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(android文件管理器用法详解)