对文件进行添加、删除、更改文件名

/*
 * 文件资源管理器再进化
 * 对文件进行添加、更改文件名、删除
 * 程序中以自定义的MyAdapter来设置显示数据传入存储文件名与
 * 文件路径的两个List对象,使用setListAdapter()将数据设置给
 * ListView。当用户单机item时,时会触犯onListItemClick(),
 * 此时程序会判断item是文件夹还是文件,是文件夹的话,就展开下
 * 一层目录,是文件的话就运行自定义的fileHandle()。fileHandle()
 * 这个方法被调用时,会先弹出含有打开文件、更改文件名、删除文件
 * 三个选项的AlertDialog。当单机任何一个item时,AlertDialog的
 * onClick()事件就会被触发,会依照所选择的item功能来运行不同的
 * 动作。
 * 当有文件被更改或被删除时,要再次运行getFileDir(),使ListView
 * 里面的文件信息是最新的。
 */
import略;

public class Ex05_15Activity extends ListActivity {
	private List<String> item = null;// 存放显示的名称
	private List<String> paths = null;// 存放文件的路径
	private String rootPath = "/";// 起始目录
	private TextView mPaht;
	private View myView;
	private EditText myEditText;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mPaht = (TextView) findViewById(R.id.mPath);
		getFileDir(rootPath);
	}

	// 取得文件架构的方法
	private void getFileDir(String filePath) {
		// 设置目前所在路径
		mPaht.setText(filePath);
		item = new ArrayList<String>();
		paths = new ArrayList<String>();
		File f = new File(filePath);
		File[] files = f.listFiles();
		if (filePath.equals(rootPath)) {
			// 第一笔设置为回到根目录
			item.add("b1");
			paths.add(rootPath);
			// 第二笔设置为回到上层
			item.add("b2");
			paths.add(f.getParent());
		}
		// 将所有文件添加到ArraryList中
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			item.add(file.getName());
			paths.add(file.getPath());
		}
		// 使用自定义的MyAdapter来将数据传入ListActivist
		setListAdapter(new MyAdapter(this, item, paths));
	}

	// 设置ListItem被按下是要做的动作
	protected void onListenerItemClick(ListView l, View v, int position, long id) {
		File file = new File(paths.get(position));
		if (file.canRead()) {
			if (file.isDirectory()) {
				// 如果是文件夹就在执行getFileDir()
				getFileDir(paths.get(position));
			} else {
				// 如果是文件则调用fileHandle()
				fileHandle(file);
			}
		} else {
			// 否则跳出AlertDialog显示权限不足
			new AlertDialog.Builder(this)
					.setTitle("提示信息")
					.setMessage("此文件不能读取或你没有足够的权限")
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
							}).show();
		}
	}

	// fileHandle()处理方法
	private void fileHandle(final File file) {
		// TODO Auto-generated method stub
		// 按下文件时OnClickListener()
		android.content.DialogInterface.OnClickListener listener1 = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if (which == 0) {
					// 选择的item为打开文件
					openFile(file);
				} else if (which == 1) {
					// 选择的item为更改文件的名字
					LayoutInflater factory = LayoutInflater
							.from(Ex05_15Activity.this);
					// 初始化myChoiceView,使用rename_alert_dialog为layyout
					myView = factory
							.inflate(R.layout.rename_alert_dialog, null);
					myEditText = (EditText) myView.findViewById(R.id.mEdit);
					// 将原始的文件名先放入到EditText中
					myEditText.setText(file.getName());
					// 一个更改文件名的Dialog的确定按钮的Listener
					android.content.DialogInterface.OnClickListener listener2 = new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							// 取得修改后的文件路径
							String modname = myEditText.getText().toString();
							final String pFile = file.getParentFile().getPath()
									+ "/";
							final String newPath = pFile + modname;
							// 判断文件是否存在
							if (new File(newPath).exists()) {
								// 排除修改文件时没修改直接送出的情况
								if (!modname.equals(file.getName())) {
									// 跳出警告 文件名重复,并确认时候修改
									new AlertDialog.Builder(
											Ex05_15Activity.this)
											.setTitle("警告!")
											.setMessage("文件已存在,是否要覆盖?")
											.setPositiveButton(
													"确定",
													new DialogInterface.OnClickListener() {

														@Override
														public void onClick(
																DialogInterface dialog,
																int which) {
															// TODO
															// Auto-generated
															// method stub
															// 单机确定,覆盖原来的文件
															file.renameTo(new File(
																	newPath));
															// 重新生成文件列表
															getFileDir(pFile);
														}
													})
											.setNegativeButton(
													"取消",
													new DialogInterface.OnClickListener() {

														@Override
														public void onClick(
																DialogInterface dialog,
																int which) {
															// TODO
															// Auto-generated
															// method stub

														}
													}).show();
								}
							} else {
								// 文件名不存在直接做修改动作
								file.renameTo(new File(newPath));
								getFileDir(pFile);
							}
						}
					};
					// 更改文件名时跳出对话框
					AlertDialog renameDialog = new AlertDialog.Builder(
							Ex05_15Activity.this).create();
					renameDialog.setView(myView);
					renameDialog.setButton("确定", listener2);
					renameDialog.setButton2("取消",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
							});
					renameDialog.show();
				} else {
					// 选择的item为删除文件
					new AlertDialog.Builder(Ex05_15Activity.this)
							.setTitle("注意")
							.setMessage("确定删除文件?")
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											file.delete();
											getFileDir(file.getParent());
										}
									})
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub

										}
									}).show();
				}
			}

		};
		// 选择一个文件时要跳出如何处理文件的ListDialog
		String[] menu = { "打开文件", "更改文件名", "删除文件" };
		new AlertDialog.Builder(Ex05_15Activity.this).setTitle("你要做什么?")
				.setItems(menu, listener1)
				.setPositiveButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).show();
	}

	// 在手机上打开文件的方法
	private void openFile(File f) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);

		// 调用getMIMEType()来取得MimeType
		String type = getMIMEType(f);
		// 设置intent的file与MimeType
		intent.setDataAndType(Uri.fromFile(f), type);
		startActivity(intent);
	}

	private String getMIMEType(File f) {
		// TODO Auto-generated method stub
		String type = "";
		String fName = f.getName();
		String end = fName
				.substring(fName.lastIndexOf("." + 1), fName.length())
				.toLowerCase();
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("wav") || end.equals("ogg")) {
			type = "audio";
		} else if (end.equals("3gp") || end.equals("mp4") || end.equals("rmvb")) {
			type = "video";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else {
			// 无法直接打开,就跳出供用户列表选择
			type = "*";
		}
		type += "/*";
		return type;
	}
}


MyAdapter.java代码如下:

/* 自定义的Adapter,继承android.widget.BaseAdapter */
public class MyAdapter extends BaseAdapter {
	/*
	 * 变量声明 mIcon1:并到根目录的图文件 mIcon2:并到第几层的图片 mIcon3:文件夹的图文件 mIcon4:文件的图片
	 */
	private LayoutInflater mInflater;
	private Bitmap mIcon1;
	private Bitmap mIcon2;
	private Bitmap mIcon3;
	private Bitmap mIcon4;
	private List<String> items;
	private List<String> paths;

	/* MyAdapter的构造符,传入三个参数 */
	public MyAdapter(Context context, List<String> it, List<String> pa) {
		/* 参数初始化 */
		mInflater = LayoutInflater.from(context);
		items = it;
		paths = pa;
		mIcon1 = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.back01);
		mIcon2 = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.back02);
		mIcon3 = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.folder);
		mIcon4 = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.doc);
	}

	/* 继承BaseAdapter,需重写method */
	@Override
	public int getCount() {
		return items.size();
	}

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

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;

		if (convertView == null) {
			/* 使用告定义的file_row作为Layout */
			convertView = mInflater.inflate(R.layout.file_row, null);
			/* 初始化holder的text与icon */
			holder = new ViewHolder();
			holder.text = (TextView) convertView.findViewById(R.id.text);
			holder.icon = (ImageView) convertView.findViewById(R.id.icon);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		File f = new File(paths.get(position).toString());
		/* 设定[并到根目录]的文字与icon */
		if (items.get(position).toString().equals("b1")) {
			holder.text.setText("Back to /");
			holder.icon.setImageBitmap(mIcon1);
		}
		/* 设定[并到第几层]的文字与icon */
		else if (items.get(position).toString().equals("b2")) {
			holder.text.setText("Back to ..");
			holder.icon.setImageBitmap(mIcon2);
		}
		/* 设定[文件或文件夹]的文字与icon */
		else {
			holder.text.setText(f.getName());
			if (f.isDirectory()) {
				holder.icon.setImageBitmap(mIcon3);
			} else {
				holder.icon.setImageBitmap(mIcon4);
			}
		}
		return convertView;
	}

	/* class ViewHolder */
	private class ViewHolder {
		TextView text;
		ImageView icon;
	}
}

布局文件很简单,在这里我就不做详细介绍了。下面我我们来看看运行后的结果:

当你权限不足时会:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值