常用的文件操作方法

java 代码
  1.   
  2. import java.io.*;   
  3.   
  4. /**  
  5.  * name:FileUtil.java  
  6.  *   
  7.  * desc: 本类是文件操作实用类,提供常用的文件操作方法。  
  8.  *   
  9.  *  
  10.  */  
  11. public class FileUtil   
  12. {   
  13.     /**  
  14.      * 方法根据指定参数名创建一个空文件  
  15.      * @param filePath 文件路径名  
  16.      * @throws IOException  
  17.      */  
  18.     public static File makeFile(String filePath)throws IOException, Exception   
  19.     {   
  20.         //参数无效   
  21.         if (filePath == null || filePath.trim().length() == 0)   
  22.         {   
  23.             throw new IllegalArgumentException("argument is not valid!");   
  24.         }   
  25.         File file = new File(filePath);   
  26.         file.getParentFile().mkdirs();   
  27.         file.createNewFile();   
  28.            
  29.         //文件不存在   
  30.         if (!file.exists())   
  31.         {   
  32.             throw new Exception("create file '"  + filePath + "' failed");   
  33.         }   
  34.         return file;   
  35.     }   
  36.        
  37.     /**  
  38.      * 方法根据指定参数创建目录  
  39.      * @param path 路径名  
  40.      * @throws IOException  
  41.      * @throws Exception  
  42.      */  
  43.     public static void makeDir(String path)throws IOException, Exception   
  44.     {   
  45.         //参数无效   
  46.         if (path == null || path.trim().length() == 0)   
  47.         {   
  48.             throw new IllegalArgumentException("argument is not valid!");   
  49.         }   
  50.         File file = new File(path);   
  51.            
  52.         //目录不存在时,创建目录   
  53.         if (!file.exists())   
  54.         {   
  55.             //创建目录失败时,延时1秒再创建   
  56.             if (!file.mkdirs())   
  57.             {   
  58.                 try  
  59.                 {   
  60.                     final long sleepTime = 1000;   
  61.                     Thread.sleep(sleepTime);   
  62.                     file.mkdirs();   
  63.                 }   
  64.                 catch(InterruptedException ie)   
  65.                 {   
  66.                     file.mkdirs();   
  67.                 }   
  68.             }   
  69.         }   
  70.            
  71.         //目录创建失败   
  72.         if (!file.exists())   
  73.         {   
  74.             throw new Exception("create dir '" + path + "' failed!");    
  75.         }   
  76.     }   
  77.   
  78.     /**  
  79.      * 方法执行文件的拷贝,不支持递归拷贝  
  80.      * @param src 源文件  
  81.      * @param dest 目的文件  
  82.      * @throws IOException  
  83.      * @throws Exception  
  84.      */  
  85.     public static void copy(File src, File dest)throws IOException, Exception   
  86.     {   
  87.         //参数无效   
  88.         if (src == null || dest == null)   
  89.         {   
  90.             throw new IllegalArgumentException("argument is not valid!");   
  91.         }   
  92.            
  93.         //参数相等   
  94.         if (src.equals(dest))   
  95.         {   
  96.             throw new IllegalArgumentException("src file equals to dest file!");   
  97.         }   
  98.            
  99.         org.apache.tools.ant.util.FileUtils fileUtils =   
  100.                                     org.apache.tools.ant.util.FileUtils.newFileUtils();   
  101.            
  102.         fileUtils.copyFile(src, dest, nulltruefalse);   
  103.     }   
  104.        
  105.     /**  
  106.      * 方法执行文件的拷贝,不支持递归拷贝  
  107.      * @param src 源文件path  
  108.      * @param dest 目的文件path  
  109.      * @throws Exception  
  110.      */  
  111.     public static void copy(String src, String dest)throws Exception   
  112.     {   
  113.         File srcFile = new File(src);   
  114.         File desFile = new File(dest);   
  115.         copy(srcFile, desFile);   
  116.     }   
  117.        
  118.     /**  
  119.      * 复制整个文件夹的内容  
  120.      * @param oldPath 源目录  
  121.      * @param newPath 目的目录  
  122.      * @return  
  123.      */  
  124.     public static void copyFolder(String oldPath, String newPath)throws  
  125.         IOException, Exception   
  126.     {   
  127.         FileInputStream input = null;   
  128.         FileOutputStream output = null;   
  129. //        try   
  130. //        {   
  131.         new File(newPath).mkdirs(); // 如果文件夹不存在 则建立新文件夹   
  132.         File a = new File(oldPath);   
  133.         String[] file = a.list();   
  134.         File temp = null;   
  135.         for (int i = 0; i < file.length; i++)   
  136.         {   
  137.             try  
  138.             {   
  139.                 if (oldPath.endsWith(File.separator))   
  140.                 {   
  141.                     temp = new File(oldPath + file[i]);   
  142.                 }   
  143.                 else  
  144.                 {   
  145.                     temp = new File(oldPath + File.separator + file[i]);   
  146.                 }   
  147.                 if (temp.isFile())   
  148.                 {   
  149.                     input = new FileInputStream(temp);   
  150.                     output = new FileOutputStream(newPath + File.separator   
  151.                             + temp.getName());   
  152.                     byte[] b = new byte[1024 * 5];   
  153.                     int len;   
  154.                     while ((len = input.read(b)) != -1)   
  155.                     {   
  156.                         output.write(b, 0, len);   
  157.                     }   
  158.                 }   
  159.                 // 如果是子文件夹   
  160.                 if (temp.isDirectory())   
  161.                 {   
  162.                     copyFolder(oldPath + File.separator + file[i], newPath   
  163.                             + File.separator + file[i]);   
  164.                 }   
  165.             }   
  166.             catch (Exception e)   
  167.             {   
  168.                 throw e;   
  169.             }   
  170.             finally  
  171.             {   
  172.                 try  
  173.                 {   
  174.                     if (output != null)   
  175.                     {   
  176.                         output.flush();   
  177.                         output.close();   
  178.                         output = null;   
  179.                     }   
  180.                        
  181.                     if (input != null)   
  182.                     {   
  183.                         input.close();   
  184.                         input = null;   
  185.                     }   
  186.                 }   
  187.                 catch (IOException ioe)   
  188.                 {   
  189.                     // do nothing;   
  190.                 }   
  191.   
  192.             }   
  193.         }   
  194.     }   
  195. // catch (Exception e)   
  196. // {   
  197. // throw e;   
  198. // }   
  199. // finally   
  200. // {   
  201. // try   
  202. // {   
  203. // output.flush();   
  204. // output.close();   
  205. // output = null;   
  206. // input.close();   
  207. // input = null;   
  208. // }   
  209. // catch(IOException ioe)   
  210. // {   
  211. // //do nothing;   
  212. // }   
  213. //   
  214. // }   
  215. // }   
  216.        
  217.     /**  
  218.      * 文件打包方法,完成一个tar包的创建  
  219.      *   
  220.      * @param tarFile  
  221.      *            tar包名  
  222.      * @param subFiles  
  223.      *            打包文件  
  224.      * @throws Exception  
  225.      */  
  226.     public static void tar(String tarFile, String[] subFiles)throws Exception   
  227.     {   
  228.         // 参数为空   
  229.         if (tarFile == null || subFiles == null)   
  230.         {   
  231.             throw new IllegalArgumentException("argument is null!");   
  232.         }   
  233.            
  234.         //压缩包格式不正确   
  235.         if (!tarFile.toLowerCase().endsWith(".tar"))   
  236.         {   
  237.             throw new IllegalArgumentException("must be a tar file!");   
  238.         }   
  239.         String currentPath = System.getProperty("user.dir");   
  240.         String commandPath = currentPath + File.separator + "tar";   
  241.         StringBuffer cmdBuffer = new StringBuffer(commandPath + " -cvf " + tarFile);   
  242.         for (int i = 0; i < subFiles.length; i++)   
  243.         {   
  244.             cmdBuffer.append(" " + subFiles[i]);   
  245.         }   
  246.         Process p = null;   
  247.         try  
  248.         {   
  249.             p = Runtime.getRuntime().exec(cmdBuffer.toString());   
  250.             //压缩文件失败   
  251.             if (p.waitFor() != 0)   
  252.             {   
  253.                 throw new IOException("tar -cvf " + tarFile + " failed!");   
  254.             }   
  255.         }   
  256.         //关闭输入输出流   
  257.         finally  
  258.         {   
  259.             if (p != null)   
  260.             {   
  261.                 p.getErrorStream().close();   
  262.                 p.getInputStream().close();   
  263.                 p.getOutputStream().close();   
  264.             }   
  265.         }   
  266.     }   
  267.     /**  
  268.      * 文件打包方法,完成一个tar包的创建  
  269.      *   
  270.      * @param tarFile  
  271.      *            tar包名  
  272.      * @param subFiles  
  273.      *            打包文件  
  274.      * @throws Exception  
  275.      */  
  276.     public static void tar(String commandPath, String tarFile, String[] subFiles)   
  277.     throws Exception   
  278.     {   
  279.         if (commandPath == null || tarFile == null || subFiles == null)   
  280.         {   
  281.             throw new IllegalArgumentException("argument is null!");   
  282.         }   
  283.            
  284.         if (!tarFile.toLowerCase().endsWith(".tar"))   
  285.         {   
  286.             throw new IllegalArgumentException("must be a tar file!");   
  287.         }   
  288.         commandPath = commandPath + "/tar";   
  289.         StringBuffer cmdBuffer = new StringBuffer(commandPath + " -cvf " + tarFile);   
  290.         for (int i = 0; i < subFiles.length; i++)   
  291.         {   
  292.             cmdBuffer.append(" " + subFiles[i]);   
  293.         }   
  294.         Process p = null;   
  295.         System.out.println(" command : " + cmdBuffer.toString());   
  296.         try  
  297.         {   
  298.             p = Runtime.getRuntime().exec(cmdBuffer.toString());   
  299.             if (p.waitFor() != 0)   
  300.             {   
  301.                 throw new IOException("tar -cvf " + tarFile + " failed!");   
  302.             }   
  303.         }   
  304.         finally  
  305.         {   
  306.             if (p != null)   
  307.             {   
  308.                 InputStream is = p.getErrorStream();   
  309.                 StringBuffer sb = new StringBuffer();   
  310.                 byte[] buffer = new byte[1024];   
  311.                 while (is.read(buffer, 0, buffer.length) != -1)   
  312.                 {   
  313.                     sb.append(new String(buffer));   
  314.                 }   
  315.                 System.out.println("error message: " + sb.toString());   
  316.                 p.getErrorStream().close();   
  317.                 p.getInputStream().close();   
  318.                 p.getOutputStream().close();   
  319.             }   
  320.         }   
  321.     }   
  322.        
  323.     public static void tar2(String tarFilePath, String baseDirPath)throws Exception   
  324.     {   
  325.         TarUtil tarUtil = new TarUtil();   
  326.         File tarFile = new File(tarFilePath);   
  327.         File baseDir = new File(baseDirPath);   
  328.         tarUtil.setDestFile(tarFile);   
  329.         tarUtil.setBasedir(baseDir);   
  330.         tarUtil.execute(null);   
  331.     }   
  332.        
  333.     /**  
  334.      * 文件解包方法,完成tar包的解压  
  335.      * @param tarFile tar包路径  
  336.      * @param storePath 存放路径  
  337.      * @throws Exception  
  338.      * @deprecated replaced by untar2()  
  339.      */  
  340.     public static void untar(String tarFile, String storePath)throws Exception   
  341.     {   
  342.         //参数无效   
  343.         if (tarFile == null || tarFile.trim().length() == 0)   
  344.         {   
  345.             throw new IllegalArgumentException("argument is empty!");   
  346.         }   
  347.            
  348.         //压缩包格式不正确   
  349.         if (!tarFile.toLowerCase().endsWith(".tar"))   
  350.         {   
  351.             throw new IllegalArgumentException("must be a tar file!");   
  352.         }   
  353.         String tarCommand = null;   
  354.         //默认存放路径   
  355.         if (storePath == null || storePath.trim().length() == 0)   
  356.         {   
  357.             tarCommand = "tar -xvf " + tarFile;   
  358.         }   
  359.            
  360.         //制定存放路径   
  361.         else  
  362.         {   
  363.             tarCommand = "tar -C " + storePath + " -xvf " + tarFile;   
  364.         }   
  365.         String path = System.getProperty("java.library.path");   
  366.         System.out.println("path is : " + path);   
  367.         String currentPath = System.getProperty("user.dir");   
  368.         String pathSeparator = System.getProperty("path.separator");   
  369.         System.setProperty("java.library.path", currentPath + pathSeparator + path);   
  370.         String command = tarCommand;   
  371.         Process p = null;   
  372.         try  
  373.         {   
  374.             p = Runtime.getRuntime().exec(command);   
  375.             if (p.waitFor() != 0)   
  376.             {   
  377.                 throw new IOException("tar -xvf " + tarFile + " failed!");   
  378.             }   
  379.         }   
  380.         catch (InterruptedException e)   
  381.         {   
  382.             e.printStackTrace();   
  383.         }   
  384.         //关闭输入输出流   
  385.         finally  
  386.         {   
  387.             if (p != null)   
  388.             {   
  389.                 p.getErrorStream().close(); &n
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值