读取android目录指定文件,通过该类可读取指定sdCard目录中的文件,对文件进行重命名,查看属性,显示文件大小,删除,打开操作,主要代码我已经加了注释,不妨各位自己看看,我就不多说了,代码如下:


import java.io.File;import java.util.ArrayList;import java.util.Collections;import java.util.List;import android.app.AlertDialog;import android.app.Dialog;import android.app.ListActivity;import android.content.DialogInterface;import android.content.Intent;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.os.Environment;import android.os.StatFs;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup.LayoutParams;import android.view.Window;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.AdapterView.OnItemLongClickListener;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;import com.cykj.oa.app.R;import com.cykj.oa.app.adapter.FileListAdapter;import com.cykj.oa.app.bean.FileBean;import com.cykj.oa.app.utils.FileUtil;public class DocumentManage extends ListActivity implements OnItemLongClickListener, OnItemSelectedListener, OnItemClickListener {String SDPATH = Environment.getExternalStorageDirectory() + "/OA-APP/";private static final String[] operate = { "删除", "重命名", "属性" };private View newAlertView;private EditText newFileName_EditText;private static String currentDirctory = "/mnt/sdcard/APP"; ScanFileTask scanFileTask;//扫描文件的任务private List files = new ArrayList();//FileBean有两个属性filename,filerulprivate boolean isListViewShow = true;private FileListAdapter fileListAdapter;private int currentItem = 0;private boolean out=false;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.listview_documentmanage);if (checkSDCard()) {// 加载文件列表fileListAdapter = new FileListAdapter(this, files, FileUtil.isZoom);setListAdapter(fileListAdapter);getListView().setOnItemLongClickListener(this);//长按显示上下文菜单getListView().setOnItemSelectedListener(this);//指的是单击一个条目getListView().setOnItemClickListener(this);scanFile(FileUtil.rootPath);//文件扫描}}/* 检查SDCard是否挂载 */public boolean checkSDCard() {if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {showMessage(getStr(com.cykj.oa.app.R.string.no_sdcard));return false;}return true;}// 短消息提示public void showMessage(String text) {Toast.makeText(this, text, Toast.LENGTH_LONG).show();}// 从资源获取字符串public String getStr(int ID) {return getResources().getString(ID);}/* 文件打开处理 */public void openFile(File f) {Intent intent = new Intent();// 采用系统默认打开方式//Log.i(TAG, "type123="+FileUtil.isOpen );//FileUtil.isOpen=1;if (FileUtil.isOpen == 0) {String type = FileUtil.getMIMEType(f);// 打开图片浏览器if (type.equals("image")) {//intent.setClass(MainActivity.this, BrowseImagesActivity.class);intent.putStringArrayListExtra("images", FileUtil.searchImages(f));startActivity(intent);}// 打开媒体播放器 else if (type.equals("audio") || type.equals("video")) {//intent.setClass(MainActivity.this, MediaPlayerActivity.class);               Bundle bl = new Bundle();bl.putString("mediapath", f.getAbsolutePath());bl.putString("mediatype", type);intent.putExtras(bl);startActivity(intent);}else if(type.equals("txt")){intent = new Intent("android.intent.action.VIEW");  intent.addCategory("android.intent.category.DEFAULT");  intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);  intent.setDataAndType (Uri.fromFile(f), "text/plain");  try {this.startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }else if(type.equals("word07")){intent = new Intent("android.intent.action.VIEW");  intent.addCategory("android.intent.category.DEFAULT");  intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);  intent.setDataAndType (Uri.fromFile(f), "application/vnd.openxmlformats-officedocument.wordprocessingml.document");  try {this.startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }else if(type.equals("word")){intent = new Intent("android.intent.action.VIEW");  intent.addCategory("android.intent.category.DEFAULT");  intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);  intent.setDataAndType (Uri.fromFile(f), "application/msword");  try {this.startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }else if(type.equals("excel07")){intent = new Intent("android.intent.action.VIEW");  intent.addCategory("android.intent.category.DEFAULT");  intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);  intent.setDataAndType (Uri.fromFile(f), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");  try {this.startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }else if(type.equals("excel")){intent = new Intent("android.intent.action.VIEW");  intent.addCategory("android.intent.category.DEFAULT");  intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);  intent.setDataAndType (Uri.fromFile(f), "application/vnd.ms-excel");  try {this.startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }else if(type.equals("powerpoint")){intent = new Intent("android.intent.action.VIEW");  intent.addCategory("android.intent.category.DEFAULT");  intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);  intent.setDataAndType (Uri.fromFile(f), "application/vnd.ms-powerpoint");  try {this.startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }else if(type.equals("powerpoint07")){intent = new Intent("android.intent.action.VIEW");  intent.addCategory("android.intent.category.DEFAULT");  intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);  intent.setDataAndType (Uri.fromFile(f), "application/vnd.openxmlformats-officedocument.presentationml.presentation");  try {this.startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }else if(type.equals("pdf")){intent = new Intent("android.intent.action.VIEW");  intent.addCategory("android.intent.category.DEFAULT");  intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);  intent.setDataAndType (Uri.fromFile(f), "application/pdf");  try {this.startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }else{intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);// 跳出列表供选择type = FileUtil.getMIMEType(f);type += "/*";// 设置intent的file与MimeTypeintent.setDataAndType(Uri.fromFile(f), type);try {this.startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }} }/* 处理文件或者目录的方法 */public void fileOrDirHandle(final File file) {/* ListItem被长按时弹出窗口的OnClickListener */android.content.DialogInterface.OnClickListener listener_list = new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {if (which == 0) {delFileOrDir(file);}else if (which == 1) {modifyFileOrDir(file);} else if (which == 2) {showProperties(file);}}};/* 选择一个文件或者目录时,跳出要如何处理文件的ListDialog */new AlertDialog.Builder(DocumentManage.this).setTitle(file.getName()).setIcon(com.cykj.oa.app.R.drawable.list).setItems(operate, listener_list).setPositiveButton(getStr(R.string.cancel),new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int which) {}}).show();}/* 修改文件夹或者文件名 */@SuppressWarnings("deprecation")public void modifyFileOrDir(File f) {final File f_old = f;LayoutInflater factory = LayoutInflater.from(DocumentManage.this);newAlertView = factory.inflate(R.layout.rename_alert, null);newFileName_EditText = (EditText) newAlertView.findViewById(R.id.rename_edit);newFileName_EditText.setText(f_old.getName());android.content.DialogInterface.OnClickListener listenerFileEdit = new DialogInterface.OnClickListener() {@SuppressWarnings({ "deprecation", "deprecation" })public void onClick(DialogInterface dialog, int which) {/* 取得修改后的文件路径 */final String modName = newFileName_EditText.getText().toString();final String pFile = f_old.getParentFile().getPath() + "/";final String newPath = pFile + modName; // 新的文件路径+文件名final File f_new = new File(newPath);System.out.println("新的文件路径+文件名"+newPath);if (f_new.exists()) {if (!modName.equals(f_old.getName())) {showMessage("指定的文件'" + modName + "'与现有文件重名,请指定另一名称!");} else {showMessage(getStr(R.string.nochange));}} else {AlertDialog rename_Dialog = showAlertDialog("确定要修改"+ (f_old.isDirectory() ? "文件夹'" : "文件'")+ f_old.getName() + "'名称为'" + modName + "'吗?");rename_Dialog.setButton(getStr(R.string.ok),new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int which) {if (f_old.isDirectory()) {if (FileUtil.checkName(newPath)) {if (f_old.renameTo(f_new)) {showMessage(getStr(R.string.modifyed));} else {showMessage(getStr(R.string.error));}} else {showMessage(getStr(R.string.error_name));}} else {if (FileUtil.checkName(newPath)) {if (f_old.renameTo(f_new)) {showMessage(getStr(R.string.modifyed));} else {showMessage(getStr(R.string.error));}} else {showMessage(getStr(R.string.error_name));}}scanFile(pFile);}});rename_Dialog.show();}};};/* 设置更改文件名点击确定后的Listener */AlertDialog renameDialog = new AlertDialog.Builder(DocumentManage.this).create();renameDialog.setView(newAlertView);renameDialog.setButton(getStr(R.string.ok), listenerFileEdit);renameDialog.setButton2(getStr(R.string.cancel),new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {}});renameDialog.show();}//打开文件private void openFileOrDir(File f) {Intent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);// 跳出列表供选择String type="/";type = FileUtil.getMIMEType(f);type += "/*";// 设置intent的file与MimeTypeintent.setDataAndType(Uri.fromFile(f), type);try {startActivity(intent);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/* 删除文件或者文件夹 */@SuppressWarnings("deprecation")private void delFileOrDir(File f) {final File f_del = f;AlertDialog delDialog = showAlertDialog("确定要删除"+ (f_del.isDirectory() ? "文件夹'" : "文件'") + f_del.getName()+ "'吗?");delDialog.setButton(getStr(R.string.ok),new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {/* 删除文件或者文件夹 */if (f_del.isDirectory()) {if (FileUtil.delDir(f_del)) {showMessage(getStr(R.string.deleted));} else {showMessage(getStr(R.string.error));}} else {if (FileUtil.delFile(f_del)) {showMessage(getStr(R.string.deleted));} else {showMessage(getStr(R.string.error));}}scanFile(f_del.getParent());setTitle(f_del.getParent());currentDirctory = f_del.getParent();}});delDialog.show();}public void showProperties(File f) {//文件属性LayoutInflater factory = LayoutInflater.from(this);View propertyview = factory.inflate(R.layout.property_layout, null);final Dialog property = new Dialog(this);property.setTitle(R.string.file_property);property.addContentView(propertyview, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));Button.OnClickListener clickListener = new Button.OnClickListener() {public void onClick(View v) {property.dismiss();}};              //??属性的间距没有设置好TextView fileName = (TextView) property.findViewById(R.id.nameinf);TextView style = (TextView) property.findViewById(R.id.style1);TextView location = (TextView) property.findViewById(R.id.location1);TextView size = (TextView) property.findViewById(R.id.size1);TextView modify = (TextView) property.findViewById(R.id.modifydata1);TextView canread = (TextView) property.findViewById(R.id.canread1);TextView canwrite = (TextView) property.findViewById(R.id.canwrite1);TextView ishidden = (TextView) property.findViewById(R.id.ishidden1);String info[] = FileUtil.getFileInfo(f).split(",");fileName.setText(info[0]);style.setText(info[1]);location.setText(info[2]);size.setText(info[3]);modify.setText(info[4]);canread.setText(info[5]);canwrite.setText(info[6]);ishidden.setText(info[7]);Button commit = (Button) property.findViewById(R.id.propertybutton);commit.setOnClickListener(clickListener);// property.setCancelable(false);//禁止通过BACK键撤销对话框。否则,有可能导致对话框消除,但是任务还在。property.show();}/* 文件操作时显示的对话框 */@SuppressWarnings("deprecation")public AlertDialog showAlertDialog(String msg) {AlertDialog alertDialog = new AlertDialog.Builder(DocumentManage.this).create();alertDialog.setTitle(R.string.notice);alertDialog.setIcon(R.drawable.alert);alertDialog.setMessage(msg);alertDialog.setButton2(getStr(R.string.cancel),new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {}});return alertDialog;}// 加载文件列表public void scanFile(String s) {if (scanFileTask != null&& scanFileTask.getStatus() == ScanFileTask.Status.RUNNING) {scanFileTask.cancel(true);}scanFileTask = new ScanFileTask();scanFileTask.execute(s);}/* 异步搜索文件 */class ScanFileTask extends AsyncTask {public ScanFileTask() {files.clear();}@Overrideprotected void onPreExecute() {super.onPreExecute();}@Overrideprotected Integer doInBackground(String... params) {//Object... params就是说可以有任意多个Object类型的参数,//也就是说可以传递0到多个Object类或子类的对象到这个方法if (params == null || params[0] == null || "".equals(params[0])) {return 0;}File file = new File(params[0]);int fileCount = 0;File[] allfiles = null;allfiles = file.listFiles();List data_dir = new ArrayList();List data_file = new ArrayList();if (allfiles != null && allfiles.length != 0) {for (File f : allfiles) {FileBean fileBean = new FileBean();if (f.isDirectory()) {fileBean.setFile(f);fileBean.setName(f.getName());fileBean.setPath(f.getPath());fileBean.setFileSize("");data_dir.add(fileBean);}}Collections.sort(data_dir, new FileBean());files.addAll(data_dir);for (File f : allfiles) {fileCount++;FileBean fileBean = new FileBean();if (f.isFile()) {fileBean.setFile(f);fileBean.setName(f.getName());fileBean.setPath(f.getPath());fileBean.setFileSize(FileUtil.getFileSize(f));data_file.add(fileBean);}}Collections.sort(data_file, new FileBean());files.addAll(data_file);} else {// 文件目录为空FileBean fileBean = new FileBean();fileBean.setName("");fileBean.setPath(null);fileBean.setFileSize("");files.add(fileBean);fileCount = 1;}return fileCount;}protected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);}protected void onPostExecute(Integer result) {super.onPostExecute(result);if (isListViewShow) {fileListAdapter.notifyDataSetChanged();// ListView} }}@Overridepublic void onItemSelected(AdapterView<?> arg0, View arg1, int position,long arg3) {currentItem = position;}@Overridepublic void onNothingSelected(AdapterView<?> arg0) {// TODO Auto-generated method stub}@Overridepublic boolean onItemLongClick(AdapterView<?> arg0, View arg1,int position, long arg3) {File file = new File(files.get(position).getPath());fileOrDirHandle(file);return true;}//点击时的效果/* SDCard告警提示 */public void isSDcardAlert() {if (FileUtil.isAlert == 1) {File path = Environment.getExternalStorageDirectory();StatFs statfs = new StatFs(path.getPath());// long blocSize = statfs.getBlockSize();long totalBlocks = statfs.getBlockCount();long availaBlock = statfs.getAvailableBlocks();if ((float) availaBlock / totalBlocks > 0.9) {showMessage(getStr(R.string.sdcard_alert));}}}/* 搜索后更新UI数据 */public void refreshView(List data) {if (data.size() == 0) {showMessage(getStr(R.string.search_result_null));return;}files.clear();files.addAll(data);if (isListViewShow) {fileListAdapter.notifyDataSetChanged();} }public void backToParent() {File file = new File(currentDirctory.trim());// 是否退出if (FileUtil.rootPath.equals(currentDirctory.trim())) {} else {scanFile(file.getParent());currentDirctory = file.getParent();this.setTitle(currentDirctory);}}@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {File file;try {file = new File(files.get(position).getPath());} catch (NullPointerException e) {return;}out=file.isDirectory();//Log.i(TAG, "type1="+file.isDirectory());if (file.isDirectory()) {scanFile(file.getPath());currentDirctory = file.getPath();this.setTitle(currentDirctory);} else {out=file.isDirectory();Log.i("dsfsd:", "type12="+file.isDirectory());openFile(file);//openFileOrDir(file);}}}


更多相关文章

  1. android 混淆文件project.properties和proguard-project.txt
  2. android存取数据方式:文件、SharedPreferences
  3. 用android-logging-log4j去实现log输出内容到sd卡中的文件的功能
  4. Android解析XML文件的三种方式
  5. android中读XML文件
  6. android带进度的文件上传
  7. android 查看解压后的.xml文件代码(axmlprinter2)
  8. 文件编码的测试(android)
  9. 【Android】使用dex2jar 与JD-Gui 反编译APK文件,查看源代码

随机推荐

  1. MySQL语句加锁的实现分析
  2. mysql 启动1067错误及修改字符集重启之后
  3. MySQL优化总结-查询总条数
  4. winx64下mysql5.7.19的基本安装流程(详细
  5. MySQL 语句注释方式简介
  6. mysql分页性能探索
  7. MySQL5.7.17安装及配置图文教程
  8. 详细解读分布式锁原理及三种实现方式
  9. mysql Community Server 5.7.19安装指南(
  10. 史上最简单的MySQL数据备份与还原教程(上