android文件管理

原创
2015/04/30 16:27
阅读数 50

<?xml version="1.0" encoding="utf-8"?>
<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>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<ListView
    android:id="@android :id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
</LinearLayout>

<?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="fill_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp" >
    </TextView>
</LinearLayout>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

 


package com.wenjian;

import java.io.File;
import java.util.ArrayList;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
    private static final String ROOT_PATH = "/";
    //存储文件名称
    private ArrayList<String> names = null;
    //存储文件路径
    private ArrayList<String> paths = null;
    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.main);
        //显示文件列表
        showFileDir(ROOT_PATH);
    }
    private void showFileDir(String path){
        names = new ArrayList<String>();
        paths = new ArrayList<String>();
        File file = new File(path);
        File[] files = file.listFiles();
        
        //如果当前目录不是根目录
        if (!ROOT_PATH.equals(path)){
            names.add("@1");
            paths.add(ROOT_PATH);
            
            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));
    }
    @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);
            }
        }
        //没有权限
        else{
            Resources res = getResources();
            new AlertDialog.Builder(this).setTitle("Message")
            .setMessage(res.getString(R.string.no_permission))
            .setPositiveButton("OK",new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    
                }
            }).show();
        }
        super.onListItemClick(l, v, position, id);
    }
    //对文件进行增删改
    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){
                    LayoutInflater factory = LayoutInflater.from(MainActivity.this);
                    view = factory.inflate(R.layout.rename_dialog, 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);
        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("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 void displayToast(String message){
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
    }
   
    public class MyAdapter extends BaseAdapter{
        private LayoutInflater inflater;
        private Bitmap 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;
            directory = BitmapFactory.decodeResource(context.getResources

(),R.drawable.ic_launcher);
            file = BitmapFactory.decodeResource(context.getResources

(),R.drawable.ic_launcher);
            //缩小图片
            directory = small(directory,0.50f);
            file = small(file,0.5f);
            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, null);
                holder = new ViewHolder();
                holder.text = (TextView)convertView.findViewById(R.id.textView);
                holder.image = (ImageView)convertView.findViewById(R.id.imageView);
                
                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(directory);
            }
            else if (names.get(position).equals("@2")){
                holder.text.setText("..");
                holder.image.setImageBitmap(directory);
            }
            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);
        }
    }
}

 

package com.wenjian; 
 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
 
import android.content.Context; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Environment; 
 
public class FileHelper { 
    private Context context; 
    private String SDPATH; 
    private String FILESPATH;
   
 
    public FileHelper(Context context) { 
        this.context = context; 
        SDPATH = Environment.getExternalStorageDirectory().getPath() + "//"; 
    } 
 
    /** 
     * 打开文件 
     * @param file 
     */ 
    public static void openFile(Context context,File file){ 
        //Uri uri = Uri.parse("file://"+file.getAbsolutePath()); 
        Intent intent = new Intent(); 
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        //设置intent的Action属性 
        intent.setAction(Intent.ACTION_VIEW); 
        //获取文件file的MIME类型 
//        String type = MIMEType.getMiMeType(file);
       
        //设置intent的data和Type属性。 
//        intent.setDataAndType(/*uri*/Uri.fromFile(file), type); 
        //跳转 
        context.startActivity(intent);     
    } 
    /** 
     * 在SD卡上创建文件 
     *  
     * @throws IOException 
     */ 
    public File creatSDFile(String fileName) throws IOException { 
        File file = new File(SDPATH + fileName); 
        file.createNewFile(); 
        return file; 
    } 
 
    /** 
     * 删除SD卡上的文件 
     *  
     * @param fileName 
     */ 
    public boolean delSDFile(String fileName) { 
        File file = new File(SDPATH + fileName); 
        if (file == null || !file.exists() || file.isDirectory()) 
            return false; 
        file.delete(); 
        return true; 
    } 
 
    /** 
     * 在SD卡上创建目录 
     *  
     * @param dirName 
     */ 
    public File creatSDDir(String dirName) { 
        File dir = new File(SDPATH + dirName); 
        dir.mkdir(); 
        return dir; 
    } 
 
    /** 
     * 删除SD卡上的目录 
     *  
     * @param dirName 
     */ 
    public boolean delSDDir(String dirName) { 
        File dir = new File(SDPATH + dirName); 
        return delDir(dir); 
    } 
    /** 
     * 修改SD卡上的文件或目录名 
     * @param fileName 
     */ 
    public boolean renameSDFile(String oldfileName, String newFileName) { 
        File oleFile = new File(oldfileName); 
        File newFile = new File(newFileName); 
        return oleFile.renameTo(newFile); 
    } 
 
    /** 
     * 拷贝SD卡上的单个文件 
     * @param path 
     * @throws IOException 
     */ 
    public boolean copySDFileTo(String srcFileName, String destFileName,String filename) 
            throws IOException { 
        File srcFile = new File(srcFileName); 
        File destFile = new File(destFileName+"/"+filename); 
        return copyFileTo(srcFile, destFile); 
    } 
 
    /** 
     * 拷贝SD卡上指定目录的所有文件 
     *  
     * @param srcDirName 
     * @param destDirName 
     * @return 
     * @throws IOException 
     */ 
    public boolean copySDFilesTo(String srcDirName, String destDirName,String filename) 
            throws IOException { 
        File srcDir = new File(srcDirName); 
        File destDir = new File(destDirName+"/"+filename); 
        return copyFilesTo(srcDir, destDir); 
    } 
 
    /** 
     * 移动SD卡上的单个文件 
     *  
     * @param srcFileName 
     * @param destFileName 
     * @return 
     * @throws IOException 
     */ 
    public boolean moveSDFileTo(String srcFileName, String destFileName) 
            throws IOException { 
        File srcFile = new File(SDPATH + srcFileName); 
        File destFile = new File(SDPATH + destFileName); 
        return moveFileTo(srcFile, destFile); 
    } 
 
    /** 
     * 移动SD卡上的指定目录的所有文件 
     * @param srcDirName 
     * @param destDirName 
     * @return 
     * @throws IOException 
     */ 
    public boolean moveSDFilesTo(String srcDirName, String destDirName) 
            throws IOException { 
        File srcDir = new File(SDPATH + srcDirName); 
        File destDir = new File(SDPATH + destDirName); 
        return moveFilesTo(srcDir, destDir); 
    } 
 
 
    /* 
     * 将文件写入sd卡。如:writeSDFile("test.txt"); 
     */ 
//  public Output writeSDFile(String fileName) throws IOException { 
//      File file = new File(SDPATH + fileName); 
//      FileOutputStream fos = new FileOutputStream(file); 
//      return new Output(fos); 
//  } 
 
    /* 
     * 在原有文件上继续写文件。如:appendSDFile("test.txt"); 
     */ 
//  public Output appendSDFile(String fileName) throws IOException { 
//      File file = new File(SDPATH + fileName); 
//      FileOutputStream fos = new FileOutputStream(file, true); 
//      return new Output(fos); 
//  } 
 
    /* 
     * 从SD卡读取文件。如:readSDFile("test.txt"); 
     */ 
//  public Input readSDFile(String fileName) throws IOException { 
//      File file = new File(SDPATH + fileName); 
//      FileInputStream fis = new FileInputStream(file); 
//      return new Input(fis); 
//  } 
     
     
    /** 
     * 建立私有文件 
     *  
     * @param fileName 
     * @return 
     * @throws IOException 
     */ 
    public File creatDataFile(String fileName) throws IOException { 
        File file = new File(FILESPATH + fileName); 
        file.createNewFile(); 
        return file; 
    } 
 
    /** 
     * 建立私有目录 
     *  
     * @param dirName 
     * @return 
     */ 
    public File creatDataDir(String dirName) { 
        File dir = new File(FILESPATH + dirName); 
        dir.mkdir(); 
        return dir; 
    } 
 
    /** 
     * 删除私有文件 
     *  
     * @param fileName 
     * @return 
     */ 
    public boolean delDataFile(String fileName) { 
        File file = new File(FILESPATH + fileName); 
        return delFile(file); 
    } 
 
    /** 
     * 删除私有目录 
     *  
     * @param dirName 
     * @return 
     */ 
    public boolean delDataDir(String dirName) { 
        File file = new File(FILESPATH + dirName); 
        return delDir(file); 
    } 
 
    /** 
     * 更改私有文件名 
     *  
     * @param oldName 
     * @param newName 
     * @return 
     */ 
    public boolean renameDataFile(String oldName, String newName) { 
        File oldFile = new File(FILESPATH + oldName); 
        File newFile = new File(FILESPATH + newName); 
        return oldFile.renameTo(newFile); 
    } 
 
    /** 
     * 在私有目录下进行文件复制 
     *  
     * @param srcFileName 
     *            : 包含路径及文件名 
     * @param destFileName 
     * @return 
     * @throws IOException 
     */ 
    public boolean copyDataFileTo(String srcFileName, String destFileName) 
            throws IOException { 
        File srcFile = new File(FILESPATH + srcFileName); 
        File destFile = new File(FILESPATH + destFileName); 
        return copyFileTo(srcFile, destFile); 
    } 
 
    /** 
     * 复制私有目录里指定目录的所有文件 
     *  
     * @param srcDirName 
     * @param destDirName 
     * @return 
     * @throws IOException 
     */ 
    public boolean copyDataFilesTo(String srcDirName, String destDirName) 
            throws IOException { 
        File srcDir = new File(FILESPATH + srcDirName); 
        File destDir = new File(FILESPATH + destDirName); 
        return copyFilesTo(srcDir, destDir); 
    } 
 
    /** 
     * 移动私有目录下的单个文件 
     *  
     * @param srcFileName 
     * @param destFileName 
     * @return 
     * @throws IOException 
     */ 
    public boolean moveDataFileTo(String srcFileName, String destFileName) 
            throws IOException { 
        File srcFile = new File(FILESPATH + srcFileName); 
        File destFile = new File(FILESPATH + destFileName); 
        return moveFileTo(srcFile, destFile); 
    } 
 
    /** 
     * 移动私有目录下的指定目录下的所有文件 
     *  
     * @param srcDirName 
     * @param destDirName 
     * @return 
     * @throws IOException 
     */ 
    public boolean moveDataFilesTo(String srcDirName, String destDirName) 
            throws IOException { 
        File srcDir = new File(FILESPATH + srcDirName); 
        File destDir = new File(FILESPATH + destDirName); 
        return moveFilesTo(srcDir, destDir); 
    } 
 
    /* 
     * 将文件写入应用私有的files目录。如:writeFile("test.txt"); 
     */ 
    public OutputStream wirteFile(String fileName) throws IOException { 
        OutputStream os = context.openFileOutput(fileName, 
                Context.MODE_WORLD_WRITEABLE); 
        return  os; 
    } 
 
    /* 
     * 在原有文件上继续写文件。如:appendFile("test.txt"); 
     */ 
//  public Output appendFile(String fileName) throws IOException { 
//      OutputStream os = context.openFileOutput(fileName, Context.MODE_APPEND); 
//      return new Output(os); 
//  } 
 
    /* 
     * 从应用的私有目录files读取文件。如:readFile("test.txt"); 
     */ 
//  public Input readFile(String fileName) throws IOException { 
//      InputStream is = context.openFileInput(fileName); 
//      return new Input(is); 
//  } 
     
     
     
   

/********************************************************************************************

**************/ 
   

/********************************************************************************************

*************/ 
    /** 
     * 删除一个文件 
     *  
     * @param file 
     * @return 
     */ 
    public boolean delFile(File file) { 
        if (file.isDirectory()) 
            return false; 
        return file.delete(); 
    } 
 
    /** 
     * 删除一个目录(可以是非空目录) 
     * @param dir 
     */ 
    public boolean delDir(File dir) { 
        if (dir == null || !dir.exists() || dir.isFile()) { 
            return false; 
        } 
        for (File file : dir.listFiles()) { 
            if (file.isFile()) { 
                file.delete(); 
            } else if (file.isDirectory()) { 
                delDir(file);// 递归 
            } 
        } 
        dir.delete(); 
        return true; 
    } 
 
    /** 
     * 拷贝一个文件,srcFile源文件,destFile目标文件 
     * @param path 
     * @throws IOException 
     */ 
    public boolean copyFileTo(File srcFile, File destFile) throws IOException { 
        if (srcFile.isDirectory() || destFile.isDirectory()) 
            return false;// 判断是否是文件 
        FileInputStream fis = new FileInputStream(srcFile); 
        FileOutputStream fos = new FileOutputStream(destFile); 
        int readLen = 0; 
        byte[] buf = new byte[1024]; 
        while ((readLen = fis.read(buf)) != -1) { 
            fos.write(buf, 0, readLen); 
        } 
        fos.flush(); 
        fos.close(); 
        fis.close(); 
        return true; 
    } 
 
    /** 
     * 拷贝目录下的所有文件到指定目录 
     *  
     * @param srcDir 
     * @param destDir 
     * @return 
     * @throws IOException 
     */ 
    public boolean copyFilesTo(File srcDir, File destDir) throws IOException { 
        if (!destDir.exists()) { 
            destDir.mkdirs(); 
         } 
        if (!srcDir.isDirectory() || !destDir.isDirectory()) 
            return false;// 判断是否是目录  
        File[] srcFiles = srcDir.listFiles(); 
        for (int i = 0; i < srcFiles.length; i++) { 
            if (srcFiles[i].isFile()) { 
                // 获得目标文件 
                File destFile = new File(destDir.getPath() + "//" 
                        + srcFiles[i].getName()); 
                copyFileTo(srcFiles[i], destFile); 
            } else if (srcFiles[i].isDirectory()) { 
                File theDestDir = new File(destDir.getPath() + "//" 
                        + srcFiles[i].getName()); 
                copyFilesTo(srcFiles[i], theDestDir); 
            } 
        } 
        return true; 
    } 
 
    /** 
     * 移动一个文件 
     *  
     * @param srcFile 
     * @param destFile 
     * @return 
     * @throws IOException 
     */ 
    public boolean moveFileTo(File srcFile, File destFile) throws IOException { 
        boolean iscopy = copyFileTo(srcFile, destFile); 
        if (!iscopy) 
            return false; 
        delFile(srcFile); 
        return true; 
    } 
 
    /** 
     * 移动目录下的所有文件到指定目录 
     * @param srcDir 
     * @param destDir 
     * @return 
     * @throws IOException 
     */ 
    public boolean moveFilesTo(File srcDir, File destDir) throws IOException { 
        if (!srcDir.isDirectory() || !destDir.isDirectory()) { 
            return false; 
        } 
        File[] srcDirFiles = srcDir.listFiles(); 
        for (int i = 0; i < srcDirFiles.length; i++) { 
            if (srcDirFiles[i].isFile()) { 
                File oneDestFile = new File(destDir.getPath() + "//" 
                        + srcDirFiles[i].getName()); 
                moveFileTo(srcDirFiles[i], oneDestFile); 
                delFile(srcDirFiles[i]); 
            } else if (srcDirFiles[i].isDirectory()) { 
                File oneDestFile = new File(destDir.getPath() + "//" 
                        + srcDirFiles[i].getName()); 
                moveFilesTo(srcDirFiles[i], oneDestFile); 
                delDir(srcDirFiles[i]); 
            } 
 
        } 
        return true; 
    } 
}

展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部