Android学习之文件管理器

来源:互联网 发布:淘宝买家怎么修改中评 编辑:程序博客网 时间:2024/06/06 01:04

这两天做了一个小小安卓手机的文件管理器,其中包括文件与文件夹的创建与删除,复制剪切和粘贴。

布局文件很简单,一个TextView显示当前路径,然后就是一个ListView显示文件夹和文件(布局文件不在给出)。

直接给出实现代码:

//获取系统的SD卡的目录File root = new File("/mnt/sdcard/");//如果 SD卡存在if (root.exists()){currentParent = root;currentFiles = root.listFiles();//使用当前目录下的全部文件、文件夹来填充ListViewinflateListView(currentFiles);//这个函数是自己写的}//下面的这个函数用于显示当前路径下的所有文件与文件夹private void inflateListView(File[] files){// 创建一个List集合,List集合的元素是MapList<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();for (int i = 0; i < files.length; i++){Map<String, Object> listItem = new HashMap<String, Object>();//如果当前File是文件夹,使用folder图标;否则使用file图标if (files[i].isDirectory()){listItem.put("icon", R.drawable.folder);}else{listItem.put("icon", R.drawable.file);}listItem.put("fileName", files[i].getName());//添加List项listItems.add(listItem);}// 创建一个SimpleAdapterSimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,R.layout.line, new String[] { "icon", "fileName" }, new int[] {R.id.icon, R.id.file_name });// 为ListView设置AdapterlistView.setAdapter(simpleAdapter);try{textView.setText("当前路径为:" + currentParent.getCanonicalPath());}catch (IOException e){e.printStackTrace();}}//然后是单击文件夹后进入文件夹,这部分功能放在listview的单击实事件中// 为ListView的列表项的单击事件绑定监听器listView.setOnItemClickListener(new OnItemClickListener(){@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id){// 用户单击了文件,直接返回,不做任何处理if (currentFiles[position].isFile())return;// 获取用户点击的文件夹下的所有文件File[] tmp = currentFiles[position].listFiles();if (tmp == null ){Toast.makeText(sdfile.this, "当前路径不可访问或该路径下没有文件",20000).show();}else {currentParent = currentFiles[position];//保存当前的父文件夹内的全部文件和文件夹currentFiles = tmp;// 再次更新ListViewinflateListView(currentFiles);if(tmp.length == 0){Toast.makeText(sdfile.this, "当前路径不可访问或该路径下没有文件",20000).show();}}}});//复制操作我是放在listview的长按事件中的,多余的代码不在给出,直接给出复制的核心代码if(filepath.isFile())//复制的是文件{sourceFilePath=filepath+"";sourceFileName=filepath.getName();//其实就是记录下源文件的路径}else if (filepath.isDirectory())//复制的是文件夹{sourceDirPath=filepath+"";sourceDirName=filepath.getName();//其实就是记录下源文件夹的路径}//有复制就要有粘贴,下面是粘贴的核心代码{//粘贴文件targetFile=currentParent+"/"+sourceFileName;try {copyFile(new File(sourceFilePath),new File(targetFile));currentFiles=currentParent.listFiles();inflateListView(currentFiles);<pre name="code" class="java">//如果是剪切操作,则加上下面这句话//delete(new File(sourceFilePath));}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//粘贴文件夹{targetDir=currentParent+"/"+sourceDirName;try {copyDirectiory(sourceDirPath,targetDir);currentFiles=currentParent.listFiles();inflateListView(currentFiles);if(CopyOrCut==2)//剪切{delete(new File(sourceDirPath));}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//复制和粘贴操作用到了copyFile和copyDirectiory两个函数,下面给出//复制文件操作public static void copyFile(File sourceFile,File targetFile)throws IOException{// 新建文件输入流并对它进行缓冲FileInputStream input=new FileInputStream(sourceFile);BufferedInputStream inBuff=new BufferedInputStream(input); // 新建文件输出流并对它进行缓冲  FileOutputStream output = new FileOutputStream(targetFile);BufferedOutputStream outBuff=new BufferedOutputStream(output); // 缓冲数组byte[] b = new byte[1024 * 5]; int len;while ((len =inBuff.read(b)) != -1) {              outBuff.write(b, 0, len);          }          // 刷新此缓冲的输出流           outBuff.flush();                    //关闭流           inBuff.close();          outBuff.close();          output.close();          input.close();  }//复制文件夹操作public static void copyDirectiory(String sourceDir, String targetDir)              throws IOException {          // 新建目标目录           (new File(targetDir)).mkdirs();          // 获取源文件夹当前下的文件或目录           File[] file = (new File(sourceDir)).listFiles();          for (int i = 0; i < file.length; i++) {              if (file[i].isFile()) {                  // 源文件                   File sourceFile=file[i];                  // 目标文件                  File targetFile=new   File(new File(targetDir).getAbsolutePath()  +File.separator+file[i].getName());                  copyFile(sourceFile,targetFile);              }              if (file[i].isDirectory()) {                  // 准备复制的源文件夹                   String dir1=sourceDir + "/" + file[i].getName();                  // 准备复制的目标文件夹                   String dir2=targetDir + "/"+ file[i].getName();                  copyDirectiory(dir1, dir2);              }          }      }  //在文件管理器中还经常有返回上一级的操作{currentParent=currentParent.getParentFile();File[] tmp;try {tmp = currentParent.listFiles();currentFiles = tmp;// 再次更新ListViewinflateListView(currentFiles);} catch (Exception e1) {// TODO Auto-generated catch blockToast.makeText(sdfile.this, "已是根目录", 2000).show();currentParent=new File(java.io.File.separator);tmp = currentParent.listFiles();currentFiles = tmp;inflateListView(currentFiles);}}//新建文件夹//弹出新建文件夹对话框final LinearLayout newfiles=(LinearLayout)getLayoutInflater().inflate(R.layout.newfiles, null);new AlertDialog.Builder(sdfile.this).setIcon(null).setTitle("请输入名称").setView(newfiles).setPositiveButton("确定", new OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubEditText editText1=(EditText)newfiles.findViewById(R.id.newfilename);String name=editText1.getText().toString();if(name.length()==0){Toast.makeText(sdfile.this, "请输入名称",20000).show();}else{File newfile = new File(currentParent+"/"+name);if (!newfile.exists()) {newfile.mkdirs();currentFiles=currentParent.listFiles();inflateListView(currentFiles);}}}}).setNegativeButton("取消", new OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stub}}).create().show();//新建文件//弹出新建文件对话框final LinearLayout newfile=(LinearLayout)getLayoutInflater().inflate(R.layout.newfiles, null);new AlertDialog.Builder(sdfile.this).setIcon(null).setTitle("请输入名称").setView(newfile).setPositiveButton("确定", new OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubEditText editText1=(EditText)newfile.findViewById(R.id.newfilename);String name=editText1.getText().toString();if(name.length()==0){Toast.makeText(sdfile.this, "请输入名称",20000).show();}else{File newfile = new File(currentParent+"/"+name+".txt");if (!newfile.exists()) {try {newfile.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}currentFiles=currentParent.listFiles();inflateListView(currentFiles);}}}}).setNegativeButton("取消", new OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stub}}).create().show();


</pre><pre name="code" class="java">

至此文件管理器完毕,当然给出的只是核心代码,并不是整个程序的复制,所以在参考时要依据自己的程序中的布局,和程序的规划参考,简单的复制肯定会出错,当然我的表达能力也欠缺,可能哪里有说的不明白的地方,望读者见谅。

0 0