Android 读取sdcard指定目录文件

读取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<FileBean> files = new ArrayList<FileBean>();//FileBean有两个属性filename,filerul
	private boolean isListViewShow = true;
	private FileListAdapter fileListAdapter;
	private int currentItem = 0;
	private boolean out=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.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 block
						e.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 block
						e.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 block
						e.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 block
						e.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 block
						e.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 block
						e.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 block
						e.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 block
						e.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与MimeType
					intent.setDataAndType(Uri.fromFile(f), type);
					try {
						this.startActivity(intent);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.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与MimeType
			intent.setDataAndType(Uri.fromFile(f), type);
			
			try {
				startActivity(intent);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.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<String, Integer, Integer> {

			public ScanFileTask() {
				files.clear();
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected 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<FileBean> data_dir = new ArrayList<FileBean>();
				List<FileBean> data_file = new ArrayList<FileBean>();
				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
				} 
			}
		}
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			currentItem = position;
			
		}


		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}


		@Override
		public 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<FileBean> 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);

			}
		}


		@Override
		public 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);
			}
			
		}
	
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值