FILEUTILS 介绍 (转载)

2023-12-10 07:48
文章标签 介绍 转载 fileutils

本文主要是介绍FILEUTILS 介绍 (转载),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Java的文件操作太基础,缺乏很多实用工具,比如对目录的操作,支持就非常的差了。如果你经常用Java操作文件或文件夹,你会觉得反复编写这些代码是令人沮丧的问题,而且要大量用到递归。
    下面是的一个解决方案,借助Apache Commons IO工具包(commons-io-1.1.jar)来简单实现文件(夹)的复制、移动、删除、获取大小等操作。


import org.apache.commons.io.FileUtils; 
import org.apache.commons.io.filefilter.*; 
import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory;


import java.io.*;


/** 
* 文件工具箱 

* @author leizhimin 2008-12-15 13:59:16 
*/ 
public final class FileToolkit { 
        private static final Log log = LogFactory.getLog(FileToolkit.class);


        /** 
         * 复制文件或者目录,复制前后文件完全一样。 
         * 
         * @param resFilePath 源文件路径 
         * @param distFolder    目标文件夹 
         * @IOException 当操作发生异常时抛出 
         */ 
        public static void copyFile(String resFilePath, String distFolder) throws IOException { 
                File resFile = new File(resFilePath); 
                File distFile = new File(distFolder); 
                if (resFile.isDirectory()) { 
                        FileUtils.copyDirectoryToDirectory(resFile, distFile); 
                } else if (resFile.isFile()) { 
                        FileUtils.copyFileToDirectory(resFile, distFile, true); 
                } 
        }


        /** 
         * 删除一个文件或者目录 
         * 
         * @param targetPath 文件或者目录路径 
         * @IOException 当操作发生异常时抛出 
         */ 
        public static void deleteFile(String targetPath) throws IOException { 
                File targetFile = new File(targetPath); 
                if (targetFile.isDirectory()) { 
                        FileUtils.deleteDirectory(targetFile); 
                } else if (targetFile.isFile()) { 
                        targetFile.delete(); 
                } 
        }


        /** 
         * 移动文件或者目录,移动前后文件完全一样,如果目标文件夹不存在则创建。 
         * 
         * @param resFilePath 源文件路径 
         * @param distFolder    目标文件夹 
         * @IOException 当操作发生异常时抛出 
         */ 
        public static void moveFile(String resFilePath, String distFolder) throws IOException { 
                File resFile = new File(resFilePath); 
                File distFile = new File(distFolder); 
                if (resFile.isDirectory()) { 
                        FileUtils.moveDirectoryToDirectory(resFile, distFile, true); 
                } else if (resFile.isFile()) { 
                        FileUtils.moveFileToDirectory(resFile, distFile, true); 
                } 
        }




        /** 
         * 重命名文件或文件夹 
         * 
         * @param resFilePath 源文件路径 
         * @param newFileName 重命名 
         * @return 操作成功标识 
         */ 
        public static boolean renameFile(String resFilePath, String newFileName) { 
                String newFilePath = StringToolkit.formatPath(StringToolkit.getParentPath(resFilePath) + "/" + newFileName); 
                File resFile = new File(resFilePath); 
                File newFile = new File(newFilePath); 
                return resFile.renameTo(newFile); 
        }


        /** 
         * 读取文件或者目录的大小 
         * 
         * @param distFilePath 目标文件或者文件夹 
         * @return 文件或者目录的大小,如果获取失败,则返回-1 
         */ 
        public static long genFileSize(String distFilePath) { 
                File distFile = new File(distFilePath); 
                if (distFile.isFile()) { 
                        return distFile.length(); 
                } else if (distFile.isDirectory()) { 
                        return FileUtils.sizeOfDirectory(distFile); 
                } 
                return -1L; 
        }


        /** 
         * 判断一个文件是否存在 
         * 
         * @param filePath 文件路径 
         * @return 存在返回true,否则返回false 
         */ 
        public static boolean isExist(String filePath) { 
                return new File(filePath).exists(); 
        }


        /** 
         * 本地某个目录下的文件列表(不递归) 
         * 
         * @param folder ftp上的某个目录 
         * @param suffix 文件的后缀名(比如.mov.xml) 
         * @return 文件名称列表 
         */ 
        public static String[] listFilebySuffix(String folder, String suffix) { 
                IOFileFilter fileFilter1 = new SuffixFileFilter(suffix); 
                IOFileFilter fileFilter2 = new NotFileFilter(DirectoryFileFilter.INSTANCE); 
                FilenameFilter filenameFilter = new AndFileFilter(fileFilter1, fileFilter2); 
                return new File(folder).list(filenameFilter); 
        }


        /** 
         * 将字符串写入指定文件(当指定的父路径中文件夹不存在时,会最大限度去创建,以保证保存成功!) 
         * 
         * @param res            原字符串 
         * @param filePath 文件路径 
         * @return 成功标记 
         */ 
        public static boolean string2File(String res, String filePath) { 
                boolean flag = true; 
                BufferedReader bufferedReader = null; 
                BufferedWriter bufferedWriter = null; 
                try { 
                        File distFile = new File(filePath); 
                        if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs(); 
                        bufferedReader = new BufferedReader(new StringReader(res)); 
                        bufferedWriter = new BufferedWriter(new FileWriter(distFile)); 
                        char buf[] = new char[1024];         //字符缓冲区 
                        int len; 
                        while ((len = bufferedReader.read(buf)) != -1) { 
                                bufferedWriter.write(buf, 0, len); 
                        } 
                        bufferedWriter.flush(); 
                        bufferedReader.close(); 
                        bufferedWriter.close(); 
                } catch (IOException e) { 
                        flag = false; 
                        e.printStackTrace(); 
                } 
                return flag; 
        } 

-------------------------------------------------------------------------------------------------------------




import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 字符串工具箱
*
* @author leizhimin 2008-12-15 22:40:12
*/
public final class StringToolkit {
  /**
  * 将一个字符串的首字母改为大写或者小写
  *
  * @param srcString 源字符串
  * @param flag     大小写标识,ture小写,false大些
  * @return 改写后的新字符串
  */
  public static String toLowerCaseInitial(String srcString, boolean flag) {
    StringBuilder sb = new StringBuilder();
    if (flag) {
        sb.append(Character.toLowerCase(srcString.charAt(0)));
    } else {
        sb.append(Character.toUpperCase(srcString.charAt(0)));
    }
    sb.append(srcString.substring(1));
    return sb.toString();
  }
  /**
  * 将一个字符串按照句点(.)分隔,返回最后一段
  *
  * @param clazzName 源字符串
  * @return 句点(.)分隔后的最后一段字符串
  */
  public static String getLastName(String clazzName) {
    String[] ls = clazzName.split("\\.");
    return ls[ls.length - 1];
  }
  /**
  * 格式化文件路径,将其中不规范的分隔转换为标准的分隔符,并且去掉末尾的"/"符号。
  *
  * @param path 文件路径
  * @return 格式化后的文件路径
  */
  public static String formatPath(String path) {
    String reg0 = "\\\\+";
    String reg = "\\\\+|/+";
    String temp = path.trim().replaceAll(reg0, "/");
    temp = temp.replaceAll(reg, "/");
    if (temp.endsWith("/")) {
        temp = temp.substring(0, temp.length() - 1);
    }
    if (System.getProperty("file.separator").equals("\\")) {
      temp= temp.replace('/','\\');
    }
    return temp;
  }
  /**
  * 格式化文件路径,将其中不规范的分隔转换为标准的分隔符,并且去掉末尾的"/"符号(适用于FTP远程文件路径或者Web资源的相对路径)。
  *
  * @param path 文件路径
  * @return 格式化后的文件路径
  */
  public static String formatPath4Ftp(String path) {
    String reg0 = "\\\\+";
    String reg = "\\\\+|/+";
    String temp = path.trim().replaceAll(reg0, "/");
    temp = temp.replaceAll(reg, "/");
    if (temp.endsWith("/")) {
        temp = temp.substring(0, temp.length() - 1);
    }
    return temp;
  }
  public static void main(String[] args) {
    System.out.println(System.getProperty("file.separator"));
    Properties p = System.getProperties();
    System.out.println(formatPath("C:///\\xxxx\\\\\\\\\\///\\\\R5555555.txt"));
//     List<String> result = series2List("asdf | sdf|siii|sapp|aaat| ", "\\|");
//     System.out.println(result.size());
//     for (String s : result) {
//         System.out.println(s);
//     }
  }
  /**
  * 获取文件父路径
  *
  * @param path 文件路径
  * @return 文件父路径
  */
  public static String getParentPath(String path) {
    return new File(path).getParent();
  }
  /**
  * 获取相对路径
  *
  * @param fullPath 全路径
  * @param rootPath 根路径
  * @return 相对根路径的相对路径
  */
  public static String getRelativeRootPath(String fullPath, String rootPath) {
    String relativeRootPath = null;
    String _fullPath = formatPath(fullPath);
    String _rootPath = formatPath(rootPath);
    if (_fullPath.startsWith(_rootPath)) {
        relativeRootPath = fullPath.substring(_rootPath.length());
    } else {
        throw new RuntimeException("要处理的两个字符串没有包含关系,处理失败!");
    }
    if (relativeRootPath == null) return null;
    else
        return formatPath(relativeRootPath);
  }
  /**
  * 获取当前系统换行符
  *
  * @return 系统换行符
  */
  public static String getSystemLineSeparator() {
    return System.getProperty("line.separator");
  }
  /**
  * 将用“|”分隔的字符串转换为字符串集合列表,剔除分隔后各个字符串前后的空格
  *
  * @param series 将用“|”分隔的字符串
  * @return 字符串集合列表
  */
  public static List<String> series2List(String series) {
    return series2List(series, "\\|");
  }
  /**
  * 将用正则表达式regex分隔的字符串转换为字符串集合列表,剔除分隔后各个字符串前后的空格
  *
  * @param series 用正则表达式分隔的字符串
  * @param regex 分隔串联串的正则表达式
  * @return 字符串集合列表
  */
  private static List<String> series2List(String series, String regex) {
    List<String> result = new ArrayList<String>();
    if (series != null && regex != null) {
        for (String s : series.split(regex)) {
          if (s.trim() != null && !s.trim().equals("")) result.add(s.trim());
        }
    }
    return result;
  }
  /**
  * @param strList 字符串集合列表
  * @return 通过“|”串联为一个字符串
  */
  public static String list2series(List<String> strList) {
    StringBuffer series = new StringBuffer();
    for (String s : strList) {
        series.append(s).append("|");
    }
    return series.toString();
  }
  /**
  * 将字符串的首字母转为小写
  *
  * @param resStr 源字符串
  * @return 首字母转为小写后的字符串
  */
  public static String firstToLowerCase(String resStr) {
    if (resStr == null) {
        return null;
    } else if ("".equals(resStr.trim())) {
        return "";
    } else {
        StringBuffer sb = new StringBuffer();
        Character c = resStr.charAt(0);
        if (Character.isLetter(c)) {
          if (Character.isUpperCase(c))
            c = Character.toLowerCase(c);
          sb.append(resStr);
          sb.setCharAt(0, c);
          return sb.toString();
        }
    }
    return resStr;
  }
  /**
  * 将字符串的首字母转为大写
  *
  * @param resStr 源字符串
  * @return 首字母转为大写后的字符串
  */
  public static String firstToUpperCase(String resStr) {
    if (resStr == null) {
        return null;
    } else if ("".equals(resStr.trim())) {
        return "";
    } else {
        StringBuffer sb = new StringBuffer();
        Character c = resStr.charAt(0);
        if (Character.isLetter(c)) {
          if (Character.isLowerCase(c))
            c = Character.toUpperCase(c);
          sb.append(resStr);
          sb.setCharAt(0, c);
          return sb.toString();
        }
    }
    return resStr;
  }
}

这篇关于FILEUTILS 介绍 (转载)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/476464

相关文章

四种Flutter子页面向父组件传递数据的方法介绍

《四种Flutter子页面向父组件传递数据的方法介绍》在Flutter中,如果父组件需要调用子组件的方法,可以通过常用的四种方式实现,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录方法 1:使用 GlobalKey 和 State 调用子组件方法方法 2:通过回调函数(Callb

Python进阶之Excel基本操作介绍

《Python进阶之Excel基本操作介绍》在现实中,很多工作都需要与数据打交道,Excel作为常用的数据处理工具,一直备受人们的青睐,本文主要为大家介绍了一些Python中Excel的基本操作,希望... 目录概述写入使用 xlwt使用 XlsxWriter读取修改概述在现实中,很多工作都需要与数据打交

java脚本使用不同版本jdk的说明介绍

《java脚本使用不同版本jdk的说明介绍》本文介绍了在Java中执行JavaScript脚本的几种方式,包括使用ScriptEngine、Nashorn和GraalVM,ScriptEngine适用... 目录Java脚本使用不同版本jdk的说明1.使用ScriptEngine执行javascript2.

Python实现NLP的完整流程介绍

《Python实现NLP的完整流程介绍》这篇文章主要为大家详细介绍了Python实现NLP的完整流程,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 编程安装和导入必要的库2. 文本数据准备3. 文本预处理3.1 小写化3.2 分词(Tokenizatio

性能测试介绍

性能测试是一种测试方法,旨在评估系统、应用程序或组件在现实场景中的性能表现和可靠性。它通常用于衡量系统在不同负载条件下的响应时间、吞吐量、资源利用率、稳定性和可扩展性等关键指标。 为什么要进行性能测试 通过性能测试,可以确定系统是否能够满足预期的性能要求,找出性能瓶颈和潜在的问题,并进行优化和调整。 发现性能瓶颈:性能测试可以帮助发现系统的性能瓶颈,即系统在高负载或高并发情况下可能出现的问题

水位雨量在线监测系统概述及应用介绍

在当今社会,随着科技的飞速发展,各种智能监测系统已成为保障公共安全、促进资源管理和环境保护的重要工具。其中,水位雨量在线监测系统作为自然灾害预警、水资源管理及水利工程运行的关键技术,其重要性不言而喻。 一、水位雨量在线监测系统的基本原理 水位雨量在线监测系统主要由数据采集单元、数据传输网络、数据处理中心及用户终端四大部分构成,形成了一个完整的闭环系统。 数据采集单元:这是系统的“眼睛”,

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

图神经网络模型介绍(1)

我们将图神经网络分为基于谱域的模型和基于空域的模型,并按照发展顺序详解每个类别中的重要模型。 1.1基于谱域的图神经网络         谱域上的图卷积在图学习迈向深度学习的发展历程中起到了关键的作用。本节主要介绍三个具有代表性的谱域图神经网络:谱图卷积网络、切比雪夫网络和图卷积网络。 (1)谱图卷积网络 卷积定理:函数卷积的傅里叶变换是函数傅里叶变换的乘积,即F{f*g}

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现

Mysql BLOB类型介绍

BLOB类型的字段用于存储二进制数据 在MySQL中,BLOB类型,包括:TinyBlob、Blob、MediumBlob、LongBlob,这几个类型之间的唯一区别是在存储的大小不同。 TinyBlob 最大 255 Blob 最大 65K MediumBlob 最大 16M LongBlob 最大 4G