`
齐晓威_518
  • 浏览: 606174 次
  • 性别: Icon_minigender_1
  • 来自: 郑州
社区版块
存档分类
最新评论

java 的 文件、文件夹 的建立、删除、复制以及移动等功能 操作

 
阅读更多

package util;   
  
import java.io.*;   
  
/**  
 * 提供对文件、文件夹 的建立、删除、复制以及移动等功能  
 * 文件操作工具类  
 * @author 金涛  
 * @version 1.0.0  
 * @date2010-3-4  
 */  
public class FileUtil {   
       
     /**  
      * 新建目录并返回该新建的目录  
      * @param folderPath String 文件夹路径  
      * @return File 新建的目录  
      */  
      public File newFolder (String folderPath) throws Exception {   
          try {   
              File folder = new File(folderPath);   
              if (!folder.exists()) {   
                  folder.mkdir();   
              }   
              return folder;   
           }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("新建目录操作出错");   
           }   
      }   
         
      /**  
       * 新建目录 如果目录路径中有不存在的目录则也进行建立 并返回该新建的目录  
       * @param folderPath String 目录路径  
       * @return File 新建的目录  
       */  
      public File newFolderAndPath (String folderPath) throws Exception {   
          try {   
              File folder = new File(folderPath);   
              if (!folder.exists()) {   
                  folder.mkdirs();   
              }   
              return folder;   
           }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("新建目录操作出错");   
           }   
      }   
         
     /**  
      * 新建文件,从数据如输入流获得数据  
      * @param filePath String 要新建文件路径及名称  
      * @param fis  
      * @return file File 返回建立的文件  
      */  
     public File newFile(String filePath, FileInputStream fis) throws Exception {   
        int len = 0;   
        try {   
             File file = new File(filePath);   
             if (!file.exists()) {   
                 file.createNewFile();   
             }   
             FileOutputStream fs = new FileOutputStream(file);   
             byte[] buffer = new byte[1024];   
             while ((len = fis.read(buffer)) != -1) {   
                 fs.write(buffer, 0, len);   
             }   
             fs.flush();   
             fs.close();   
             fis.close();   
             return file;   
         }catch (Exception e) {   
             e.printStackTrace();   
             throw new Exception ("新建一个文件出错");   
         }   
     }   
        
     /**  
      * 新建一个字符文件,并向其中添加内容  
      * @param filePath 新建的带文件名的文件路径  
      * @param conttent 文件内容  
      * @return file File 返回建立的文件  
      * @throws Exception  
      */  
     public File newFile(String filePath,String conttent) throws Exception {   
         try{   
             File file = new File(filePath);   
             if (!file.exists()) {   
                 file.createNewFile();   
             }   
             FileWriter resultFile = new FileWriter(filePath);   
             PrintWriter myFile = new PrintWriter(resultFile);   
             String strContent = conttent;   
             myFile.println(strContent);   
             myFile.close();   
             resultFile.close();   
             return file;   
         }catch (Exception e) {   
             e.printStackTrace();   
             throw new Exception ("新建一个字符文件出错");   
         }   
     }   
        
     /**  
      * 从文件中获得字节数组  
      * @param f File文件  
      * @return  
      */  
     private byte[] getBytesFromFile(File f) throws Exception {   
        int len = 0;   
        if (f == null && !f.exists()) {   
            return null;   
        }   
        try {   
            FileInputStream stream = new FileInputStream(f);   
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);   
            byte[] b = new byte[1024];   
            while ((len = stream.read(b)) != -1)   
                out.write(b, 0, len);   
            stream.close();   
            out.close();   
            return out.toByteArray();   
        }catch (Exception e) {   
            e.printStackTrace();   
            throw new Exception ("从文件中获得字节数组出错");   
        }   
    }   
        
        
    /**  
     * 不抛出异常的文件删除  
     * @param file java.io.File 需要删除的文件对象   
     * @return boolean true = 文件删除成功, false = 文件删除失败  
     */  
     public boolean delFileOnNoE(File file){   
         try{   
             return file.delete();   
         }catch (Exception e) {   
             e.printStackTrace();   
             return false;   
         }   
     }   
        
     /**  
      * 可以抛出异常的文件删除  
      * @param file java.io.File 需要删除的文件对象   
      * @return boolean true = 文件删除成功, false = 文件删除失败   
      */  
     public boolean delFileOnE(File file) throws Exception{   
         try{   
             if (file.delete()) {   
                 return true;   
             }else {   
                 throw new Exception("不能删除文件"+file.getPath()+File.separator+file.getName());   
             }   
         }catch (Exception e) {   
             e.printStackTrace();   
             throw new Exception("删除文件异常"+e.getMessage());   
         }   
     }   
        
         
     /**  
      * 根据路径删除文件  
      * @param filePathAndName String 文件路径及名称   
      * @return boolean (true= 删除成功,false= 删除失败)  
      */  
      public boolean delFile(String filePathAndName) {   
          try {   
              String filePath = filePathAndName;   
              java.io.File myDelFile = new java.io.File(filePath);   
              if (!myDelFile.delete()) {   
                  throw new Exception ("删除文件失败");   
              }   
              return true;   
          }catch (Exception e) {   
              System.out.println("删除文件操作出错");   
              e.printStackTrace();   
              return false;   
          }   
      }   
         
     /**  
      * 根据路径删除文件夹  
      * @param path String 文件夹路径  
      * @param isThrowException boolean (true = 删除文件出错时抛出异常,false = 删除文件出错时不抛出异常,继续执行)  
      * @param isDel boolean (true= 删除整个文件夹, false=只删除文件夹里的所有内容)  
      * @return long (当isThrowException为false时:0 = 删除文件夹成功,>0 表示删除文件夹下边的文件时,出错的个数  
      *               当isThrowException为true时:0 = 删除文件夹成功,当删除出错时会抛出异常)  
      * @exception  
      */  
      private long delFileOp(String path,boolean isDel,boolean isThrowException)throws Exception {   
          long flag = 0l;   
          try {   
              File dir = new File(path);//获得该文件夹   
              if (dir.exists() && dir.isDirectory()) {   
                  File[] dirAndFiles = dir.listFiles();//返回此抽象路径中的文件和目录   
                  for (int i=0; i<dirAndFiles.length; i++) {   
                      if (dirAndFiles[i].isDirectory()) {   
                          flag += delFileOp(dirAndFiles[i].getAbsolutePath(),true,isThrowException);//要删除子文件夹里的所有内容   
                      }else {   
                          if (isThrowException) {   
                              if (!this.delFileOnE(dirAndFiles[i])) {   
                                  flag++;   
                              }   
                          }else{   
                              if (!this.delFileOnNoE(dirAndFiles[i])) {   
                                  flag++;   
                              }   
                          }   
                      }   
                  }   
                  if (dir.listFiles().length==0 && isDel) {//删除自身是空的文件夹   
                     if (isThrowException) {   
                          if (!this.delFileOnE(dir)) {   
                              flag++;   
                          }   
                      }else{   
                          if (!this.delFileOnNoE(dir)) {   
                              flag++;   
                          }   
                      }   
                 }   
             }   
          }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("删除文件夹出错"+e.getMessage());   
          }   
          return flag;   
      }   
         
      /**  
       * 根据路径删除文件夹里的内容  
       * @param folderPath String 文件夹路径  
       * @param isThrowException boolean (true = 删除文件出错时抛出异常,false = 删除文件出错时不抛出异常,继续执行)  
       * @return long (当isThrowException为false时:0 = 删除文件夹成功,>0 表示删除文件夹下边的文件时,出错的个数  
       *               当isThrowException为true时: 0 = 删除文件夹成功,当删除出错时会抛出异常)  
       * @throws Exception   
       */  
      public long delFolderContent(String folderPath,boolean isThrowException) throws Exception {   
          try {   
              return delFileOp(folderPath,false,isThrowException); //删除完里面所有内容   
          }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("删除文件夹内容出错"+e.getMessage());   
          }   
      }    
         
      /**  
       * 根据路径删除文件夹  
       * @param filePathAndName String 文件夹路径及名称  
       * @param isThrowException boolean (true = 删除文件出错时抛出异常,false = 删除文件出错时不抛出异常,继续执行)  
       * @return long (当isThrowException为false时:0 = 删除文件夹成功,>0 表示删除文件夹下边的文件时,出错的个数  
       *               当isThrowException为true时:0 = 删除文件夹成功,当删除出错时会抛出异常)  
       * @exception  
       */  
      public long delFolder(String folderPath,boolean isThrowException) throws Exception {   
          try {   
              return delFileOp(folderPath,true,isThrowException); //删除完里面所有内容   
          }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("删除文件夹出错"+e.getMessage());   
          }   
      }   
  
      /**  
       * 复制单个文件  
       * @param oldPath String 原文件路径 得包括文件名  
       * @param newPath String 目标路径 得包括文件名  
       */  
      public void copyFile(String oldPath, String newPath) throws Exception{   
          int b = 0;   
          try {   
              File oldFile = new File(oldPath);   
              if (oldFile.exists()) {//文件存在时   
                  InputStream ins = new FileInputStream(oldPath);   
                  FileOutputStream fs = new FileOutputStream(newPath);   
                  byte[] buffer = new byte[1024];   
                  while ((b = ins.read(buffer)) != -1) {//一次读入1024个字节 如果效率低可以重新改变缓冲区大小   
                     fs.write(buffer, 0, b);   
                  }   
                  fs.flush();   
                  fs.close();   
                  ins.close();   
              }   
          }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("复制单个文件操作出错");   
          }   
      }   
  
      /**  
       * 复制文件夹到另一个目录  
       * @param copyPath String 原文件夹路径  
       * @param targetPath String 目标文件夹路径  
       * @param isCopy boolean true=复制文件夹到另一个目录,false=只复制文件夹下面的文件到另一个目录  
       * @return boolean  
       */  
      private void copyFolderOp(String copyPath, String targetPath,boolean isCopy) throws Exception {   
          FileInputStream ins = null;   
          FileOutputStream os = null;   
          int len = 0;   
          try {   
              File copyFolder = new File(copyPath);   
              File targetFolder = new File(targetPath);   
              File newFolder = null;   
              if(!targetFolder.exists() && !targetFolder.mkdirs()) {//如果目标路径不存在,则建立目标路径   
                  throw new Exception ("文件夹:"+targetPath+"建立失败");   
              }   
              if (copyFolder.exists() && copyFolder.isDirectory()) {   
                  if (isCopy) {   
                      newFolder = this.newFolderAndPath(targetPath +File.separator+ copyFolder.getName());//在目标文件夹内建立原文件夹   
                  }else {   
                      newFolder = targetFolder;   
                  }   
                  File [] oldFiles = copyFolder.listFiles();   
                  for (int i=0; i <oldFiles.length; i++) {   
                     if(oldFiles[i].isFile()){   
                          this.copyFile(oldFiles[i].getPath(),newFolder.getPath()+ File.separator +oldFiles[i].getName());   
                     }else {//如果是子文件夹   
                         copyFolderOp(oldFiles[i].getPath(),newFolder.getPath(),true);   
                     }   
                  }   
              }   
          }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("复制整个文件夹出错");   
          }   
      }   
         
      /**  
       * 复制文件夹里的内容到指定目录  
       * @param copyPath String 原文件夹路径  
       * @param targetPath String 目标文件夹路径  
       * @throws Exception   
       */  
      public void copyFolderContent(String copyPath, String targetPath) throws Exception {   
          try{   
              copyFolderOp(copyPath,targetPath,false);   
          }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("复制文件夹"+copyPath+"里的内容,到"+targetPath+"目录出错");   
          }   
      }   
         
      /**  
       * 复制整个文件夹到指定目录  
       * @param copyPath  
       * @param targetPath  
       * @throws Exception  
       */  
      public void copyAllFolder(String copyPath, String targetPath) throws Exception {   
          try{   
              copyFolderOp(copyPath,targetPath,true);   
          }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("复制整个文件夹"+copyPath+",到"+targetPath+"目录出错");   
          }   
      }   
         
         
      /**  
       * 移动文件到指定目录  
       * @param oldPath String   
       * @param newPath String   
       */  
      public void moveFile(String oldPath, String newPath) throws Exception {   
          try{   
              copyFile(oldPath, newPath);   
              delFile(oldPath);   
          }catch (Exception e) {   
              e.printStackTrace();   
              throw new Exception ("移动文件"+oldPath+"到"+newPath+"出错");   
          }   
      }   
  
      /**  
       * 移动文件夹到指定目录  
       * @param oldPath String  
       * @param newPath String  
       */  
      public void moveFolder(String oldPath, String newPath) throws Exception {   
          try{   
              copyFolderOp(oldPath, newPath,true);   
              delFolder(oldPath,false);   
          }catch(Exception e) {   
              e.printStackTrace();   
              throw new Exception ("移动文件夹"+oldPath+"到"+newPath+"出错");   
          }   
      }   
       
   /**  
    * @param args  
    */  
       
    public static void main(String[] args){   
        FileUtil fu = new FileUtil();   
        try{   
            fu.newFile("E:\\test\\test.html", "<html><head><title></title></head><body><a href="http://www.sina.com" mce_href="http://www.sina.com" >测试</a></body></html>");   
            fu.copyAllFolder("E:\\test", "E:\\tmp");   
            fu.delFolder("E:\\tmp\\test",true);   
        }catch(Exception e) {   
            e.printStackTrace();   
        }   
    }   
       

 

分享到:
评论

相关推荐

     一.JAVA程序传送到手机的方法:

    打开文件夹把两个文件都移动到手机自身的"其他文件夹"  最后,在待机状态下输入*#9998*4678255#,点JAD,然后安装。注意必须是有JAD文件 的,一定要是存在本机(切记是本机)的其他文件夹里。  3)联想i908JAVA...

    基于JAVA的RSA文件加密软件的设计与实现.zip

    文件加密软件指的是以某种特殊的算法改变原有的信息数据,使得未...软件采用了成熟先进的加密算法、加密方法和文件系统底层驱动,使文件加密和文件夹加密后的达到超高的加密强度,并且还能够防止被删除、复制和移动。

    Java开发实战1200例(第1卷).(清华出版.李钟尉.陈丹丹).part3

    本书是第II卷,以开发人员在项目开发中经常遇到的问题和必须掌握的技术为中心,介绍了应用Java进行桌面程序开发各个方面的知识和技巧,主要包括Java语法与面向对象技术、Java高级应用、窗体与控件应用、文件操作典型...

    ant1.9资源

    同时在antstudy工程的根目录下建立build.xml文件,在该文件中编译src目录下的java文件,并将编译后的class文件放入build/classes目录中,在编译前,需清除classes目录,该文件的内容如下: ...

    Flash格斗动画的动作设计和动作的制作.doc

    (请下载这个视频演示: 点击下载此文件它将会很清楚告诉你整个过程的操作, 你会发现我在一些功能的操作上都使用的快捷键, 所以操作的过程很快, 如果有不明白的地方请把教程内容多阅读几遍, 这几乎是很有必要的!...

    新版Android开发教程.rar

    � Android 更像一款桌面环境为 Java 的 Linux 操作系统。有助于 Google 实现其 " 随时随地为每个人提供信 息 " 的企业战略。 HTC HTC HTC HTC Dream/G1 Dream/G1 Dream/G1 Dream/G1 具体配置 硬件 3.17 英寸 HVGA ...

    springmybatis

    3. 建立与数据库对应的 java class,以及映射文件. 在src_user下建立package:com.yihaomen.mybatis.model ,并在这个 package 下建立 User 类: 程序代码 程序代码 package com.yihaomen.mybatis.model; public class...

    fso浏览54646465465464564

    EchoClose "目标文件夹在源文件夹内,非法操作!" Exit Sub End If '================ If Not IsFolder(Fname) Then EchoClose "目标文件夹不存在!" ElseIf IsFile(sName) Then Set oFile=oFso....

    IIS6.0 IIS,互联网信息服务

    在这里可以管理的范围主要包括对Web站点和FTP站点进行的新建、修改、启动、停止和删除等操作。 [编辑本段]有关IIS的常见问题解答  四、本部分常见问题解答 Q:在上文中所涉及到的网址中,有的加了“http://”,有的...

    asp.net知识库

    使用Relations建立表之间的关系并却使用PagedDataSource类对DataList进行分页 通过作业,定时同步两个数据库 SQLSERVER高级注入技巧 利用反射实现ASP.NET控件和数据实体之间的双向绑定,并且在客户端自动验证输入的...

    Oracle SQL高级编程(资深Oracle专家力作,OakTable团队推荐)--随书源代码

     通过提示及配置文件等来控制执行计划;  在程序中优化查询而无需改动代码。  作为Oracle SQL经典著作之一,本书为SQL开发人员指明了前行的方向,赋予了他们不断开拓的动力。 作者简介  KAREN MORTON 研究...

Global site tag (gtag.js) - Google Analytics