文件管理器(草稿篇)


package com.example.wenjianguanli;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends ListActivity {
private String rootPath;
File root;
private TextView mPath;
private String mOldFilePath = "";
private String mNewFilePath = "";
private long size;
private long newF;
private Handler handler;
private ProgressDialog myProgressDialog;
//存储文件名称
private ArrayList<String> names = null;
//存储文件路径
private ArrayList<String> paths = null;
private GridView mGrid;
private int[] girdview_image = {R.drawable.menu_create,R.drawable.menu_palse,R.drawable.menu_palse,R.drawable.menu_exit};
private String[] gridview_title = {"创建","粘贴","移动","退出"};
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.activity_main);
//初始化菜单视图
initGridViewMenu();
//初始化菜单监听器
initMenuListener();




File root= Environment.getExternalStorageDirectory();
rootPath=root.toString();
mPath = (TextView) findViewById(R.id.mPath);
//显示文件列表
showFileDir(rootPath);
}

/**为GridView配饰菜单资源*/
private void initGridViewMenu(){
mGrid=(GridView)findViewById(R.id.grid);
//设置列数
mGrid.setNumColumns(4);
//设置剧中对齐
mGrid.setGravity(Gravity.CENTER);
//设置水平,垂直间距为10
mGrid.setVerticalSpacing(10);
mGrid.setHorizontalSpacing(10);
mGrid.setBackgroundResource(R.drawable.background);
//设置适配器
mGrid.setAdapter(getMenuAdapter(gridview_title,girdview_image));
}

/**菜单适配器*/
private SimpleAdapter getMenuAdapter(String[] menuNameArray,
int[] imageResourceArray) {
//数组列表用于存放映射表
ArrayList<HashMap<String, Object>> mData = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < menuNameArray.length; i++) {
HashMap<String, Object> mMap = new HashMap<String, Object>();
//将“image”映射成图片资源
mMap.put("image", imageResourceArray[i]);
//将“title”映射成标题
mMap.put("title", menuNameArray[i]);
mData.add(mMap);
}
//新建简单适配器,设置适配器的布局文件,映射关系
SimpleAdapter mAdapter = new SimpleAdapter(this, mData,R.layout.item_menu, new String[] { "image", "title" },new int[] { R.id.item_image, R.id.item_text });
return mAdapter;
}

/**菜单项的监听*/
protected void initMenuListener(){
mGrid.setOnItemClickListener(new OnItemClickListener(){

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
switch(arg2){
//创建文件夹
case 0:
createFolder();
break;
//粘贴文件
case 1 :
palseFile();
break;
//退出
case 2 :
moveFile();
break;
case 3:
MainActivity.this.finish();
break;
}
}
});
}

/**粘贴*/


private void palseFile(){
mNewFilePath = mCurrentFilePath+java.io.File.separator+mCopyFileName;//得到新路径
Log.d("copy", "mOldFilePath is "+mOldFilePath+"| mNewFilePath is "+mNewFilePath+"| isCopy is "+isCopy);
if(!mOldFilePath.equals(mNewFilePath)&&isCopy == true){//在不同路径下复制才起效
if(!new File(mNewFilePath).exists()){
/*
myProgressDialog=new ProgressDialog(MainActivity.this);
myProgressDialog.setMax(100);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myProgressDialog.setTitle("正在复制文件");
myProgressDialog.setCancelable(false);
new Thread(new Runnable() {
@Override
public void run() {


runOnUiThread(new Runnable() {
public void run() {


copyFile(mOldFilePath,mNewFilePath);

Toast.makeText(MainActivity.this, "执行了粘贴", Toast.LENGTH_SHORT).show();
showFileDir(mCurrentFilePath);
}
});

try {
myProgressDialog.setProgress((int)(100*newF/size));
if (myProgressDialog.getProgress()>=100)
{
//关闭进度条
myProgressDialog.dismiss();
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}).start();

*/




}else{
new AlertDialog.Builder(MainActivity.this)
.setTitle("提示!")
.setMessage("该文件名已存在,是否要覆盖?")
.setPositiveButton("确定", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
copyFile(mOldFilePath,mNewFilePath);
showFileDir(mCurrentFilePath);
}
})
.setNegativeButton("取消", null).show();
}
}else{
Toast.makeText(MainActivity.this, "未复制文件!", Toast.LENGTH_LONG).show();
}
}
private void moveFile(){
mNewFilePath = mCurrentFilePath+java.io.File.separator+mCopyFileName;
if(isCut == true){
if(!new File(mNewFilePath).exists()){
new File(mOldFilePath).renameTo(new File(mNewFilePath));
Toast.makeText(MainActivity.this, "执行了移动", Toast.LENGTH_SHORT).show();
showFileDir(mCurrentFilePath);
}
}
}

private String mNewFolderName = "";
private File mCreateFile;
private RadioGroup mCreateRadioGroup;
private static int mChecked;
/**创建文件夹的方法:当用户点击软件下面的创建菜单的时候,是在当前目录下创建的一个文件夹
* 静态变量mCurrentFilePath存储的就是当前路径
* java.io.File.separator是JAVA给我们提供的一个File类中的静态成员,它会根据系统的不同来创建分隔符
* mNewFolderName正是我们要创建的新文件的名称,从EditText组件上得到的*/
private void createFolder(){
//用于标识当前选中的是文件或者文件夹
mChecked = 2;
LayoutInflater mLI = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//初始化对话框布局
final LinearLayout mLL = (LinearLayout)mLI.inflate(R.layout.create_dialog, null);
mCreateRadioGroup = (RadioGroup)mLL.findViewById(R.id.radiogroup_create);
final RadioButton mCreateFileButton = (RadioButton)mLL.findViewById(R.id.create_file);
final RadioButton mCreateFolderButton = (RadioButton)mLL.findViewById(R.id.create_folder);
//设置默认为创建文件夹
mCreateFolderButton.setChecked(true);
//为按钮设置监听器
mCreateRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
//当选择改变时触发
public void onCheckedChanged(RadioGroup arg0, int arg1) {
if(arg1 == mCreateFileButton.getId()){
mChecked = 1;
}else if(arg1 == mCreateFolderButton.getId()){
mChecked = 2;
}
}
});
//显示对话框
Builder mBuilder = new AlertDialog.Builder(MainActivity.this)
.setTitle("新建")
.setView(mLL)
.setPositiveButton("创建", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
//或者用户输入的名称
mNewFolderName = ((EditText)mLL.findViewById(R.id.new_filename)).getText().toString();
if(mChecked == 1){
try {
mCreateFile = new File(mCurrentFilePath+java.io.File.separator+mNewFolderName+".txt");
mCreateFile.createNewFile();
//刷新当前目录文件列表
showFileDir(mCurrentFilePath);
} catch (IOException e) {
Toast.makeText(MainActivity.this, "文件名拼接出错..!!", Toast.LENGTH_SHORT).show();
}
}else if(mChecked == 2){
mCreateFile = new File(mCurrentFilePath+java.io.File.separator+mNewFolderName);
if(!mCreateFile.exists()&&!mCreateFile.isDirectory()&&mNewFolderName.length() != 0){
if(mCreateFile.mkdirs()){
//刷新当前目录文件列表
showFileDir(mCurrentFilePath);
}else{
Toast.makeText(MainActivity.this, "创建失败,可能是系统权限不够,root一下?!", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "文件名为空,还是重名了呢?", Toast.LENGTH_SHORT).show();
}
}
}
}).setNeutralButton("取消", null);
mBuilder.show();
}

public static String mCurrentFilePath = "";
/**根据给定的一个文件夹路径字符串遍历出这个文
* 件夹中包含的文件名称并配置到ListView列表中*/
private void showFileDir(String path){

try {
mCurrentFilePath = path;
mPath.setText(path);
names = new ArrayList<String>();
paths = new ArrayList<String>();
File file = new File(path);
File[] files = file.listFiles();

//如果当前目录不是根目录
if (!rootPath.equals(path)){
names.add("@1");
paths.add(rootPath);

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));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@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);
}
}
super.onListItemClick(l, v, position, id);
}
//对文件进行增删改
private String mCopyFileName;
private boolean isCut=false;
private boolean isCopy = false;
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){
Toast.makeText(MainActivity.this, "移动到", Toast.LENGTH_SHORT).show();
isCut=true;
//取得移动文件的名字
mCopyFileName = file.getName();
//记录移动文件的路径
mOldFilePath = mCurrentFilePath+java.io.File.separator+mCopyFileName;
}
//复制
else if(which==2){
Toast.makeText(MainActivity.this, "已复制!", Toast.LENGTH_SHORT).show();
//复制标志位,表明已复制文件
isCopy = true;

size=file.length();
//取得复制文件的名字
mCopyFileName = file.getName();
//记录复制文件的路径
mOldFilePath = mCurrentFilePath+java.io.File.separator+mCopyFileName;
}
//修改文件名
else if(which == 3){
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
view = factory.inflate(R.layout.rename, 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); //默认的跳转类型,将Activity放到一个新的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("mid")||
end.equals("xmf")||end.equals("ogg")|| 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 int i;
FileInputStream fis;
FileOutputStream fos;
//复制文件
private void copyFile(String oldFile,String newFile){
try {
fis = new FileInputStream(oldFile);
fos = new FileOutputStream(newFile);

do{
//逐个byte读取文件,并写入另一个文件中
if((i = fis.read()) != -1){
newF=i;
fos.write(i);
}
}while(i != -1);
//关闭输入文件流
if(fis != null){
fis.close();
}
//关闭输出文件流
if(fos != null){
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


private void displayToast(String message){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}


MyAdapter类

package com.example.wenjianguanli;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;

public class MyAdapter extends BaseAdapter{
private LayoutInflater inflater;
private Bitmap back01,back02,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;
back01 = BitmapFactory.decodeResource(context.getResources(),R.drawable.back01);
back02= BitmapFactory.decodeResource(context.getResources(),R.drawable.back02);
directory = BitmapFactory.decodeResource(context.getResources(),R.drawable.folder);
file = BitmapFactory.decodeResource(context.getResources(),R.drawable.doc);
//缩小图片
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_row, null);
holder = new ViewHolder();
holder.text = (TextView)convertView.findViewById(R.id.text);
holder.image = (ImageView)convertView.findViewById(R.id.icon);

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(back01);
}
else if (names.get(position).equals("@2")){
holder.text.setText("返回上一层..");
holder.image.setImageBitmap(back02);
}
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);
}
}


权限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
xml
activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/mPath"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:singleLine="true" >
</TextView>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/mPath"
android:layout_marginBottom="70dp"
/>
<GridView
android:id="@+id/grid"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true"></GridView>
</RelativeLayout>


create_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- 二选一 -->
<RadioGroup
android:id="@+id/radiogroup_create"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- 创建文件选项 -->
<RadioButton
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="文本文件"
android:id="@+id/create_file" />
<!-- 创建文件夹选项 -->
<RadioButton
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="文件夹"
android:id="@+id/create_folder" />
</RadioGroup>
<!-- 文本框,供用户填写文件名称 -->
<EditText
android:layout_height="wrap_content"
android:id="@+id/new_filename"
android:layout_width="fill_parent"
android:hint="请输入文件名"
android:singleLine="true" />
</LinearLayout>

file_row.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="6px"
>
<ImageView android:id="@+id/icon"
android:layout_width="30dip"
android:layout_height="30dip"
>
</ImageView>
<TextView android:id="@+id/text"
android:layout_gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#767676"
>
</TextView>
</LinearLayout>
</LinearLayout>

item_menu.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout_Item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dip">
<!-- 用于显示菜单的图片 -->
<ImageView
android:id="@+id/item_image"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="45dp"></ImageView>
<!-- 用于显示菜单的文字 -->
<TextView
android:layout_below="@id/item_image"
android:id="@+id/item_text"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"></TextView>
</RelativeLayout>


rename.xml

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值