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 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 series2List(String series) {

return series2List(series, "\\|");

}

/**

* 将用正则表达式regex分隔的字符串转换为字符串集合列表,剔除分隔后各个字符串前后的空格

*

* @param series 用正则表达式分隔的字符串

* @param regex 分隔串联串的正则表达式

* @return 字符串集合列表

*/

private static List series2List(String series, String regex) {

List result = new ArrayList();

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 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;

}

}

java fileutils 文件夹_java文件操作---FileUtils相关推荐

  1. java生成文件夹_java 文件和文件夹的创建

    File类的常见方法 1.创建. boolean createNewFile(); //创建文件 boolean mkdir();创建文件夹 boolean mkdirs();创建多级文件夹. 2.删 ...

  2. java 接口文件夹_Java NIO.2 使用Path接口来监听文件、文件夹变化

    Java7对NIO进行了大的改进,新增了许多功能: •对文件系统的访问提供了全面的支持 •提供了基于异步Channel的IO 这些新增的IO功能简称为 NIO.2,依然在java.nio包下. 早期的 ...

  3. java多线程 文件夹_Java多线程遍历文件夹,广度遍历加多线程加深度遍历结合

    复习IO操作,突然想写一个小工具,统计一下电脑里面的Java代码量还有注释率,最开始随手写了一个递归算法,遍历文件夹,比较简单,而且代码层次清晰,相对易于理解,代码如下:(完整代码贴在最后面,前面是功 ...

  4. java 读文件夹_java怎么读取读取文件夹下的所有文件夹和文件?

    下是实现的代码:package com.borland.samples.welcome; import java.io.FileNotFoundException; import java.io.IO ...

  5. java怎么读取文件夹下的_java怎么读取读取文件夹下的所有文件夹和文件?

    下是实现的代码:package com.borland.samples.welcome; import java.io.FileNotFoundException; import java.io.IO ...

  6. java 文件大小统计工具类_Java获取文件大小,文件夹内文件个数的工具类

    package cn.edu.hactcm.cfcms.utils; import java.io.File; import java.io.FileInputStream; import java. ...

  7. java 获取子文件夹_JAVA之File类 获取一个目录下的所有文件夹和文件,包括子文件夹和子文件...

    package ioTest.io3; import java.io.File; /* * 获取一个目录下的所有文件夹和文件,包括子文件夹和子文件 . * 并将文件夹和文件名称打印在控制台上面.并且要 ...

  8. java 包含文件_java 文件夹拷贝(文件夹里包含文件和文件夹) 代码

    java代码实现文件夹拷贝,文件夹可能包含文件夹和文件import java.io.BufferedReader; import java.io.File; import java.io.FileIn ...

  9. java生成文件夹_java 创建文件夹和文件 汇总

    前提 D盘存在文件夹a,文件D:/a/b/c 不存在 1.默认file.exists().file.isFile().file.isDirectory() 均返回 false 2.使用file.cre ...

最新文章

  1. 博弈最高位POJ 1704(Georgia and Bob-Nim博弈)
  2. 汇编语言基础 debug的使用
  3. SpringMVC的数据响应-回写数据-直接回写json格式字符串(应用)
  4. 输入5个学生的名字(英文),使用冒泡排序按从大到小排序。 提示:涉及到字符串数组,一个字符串是一个一维字符数组;一个 字符串数组就是一个二维字符数组。...
  5. 修改placeorder html,数字分发Web服务DDWSPlaceOrder-服务手册-Partner.PDF
  6. 抓包工具tcpdump和tshark
  7. ajax 执行成功 modal 关闭_Ajax请求中的async:false/true的作用
  8. 关于rdp wrapper的not supported、not listening问题的可能解决办法
  9. C# Winform SplitContainer组件创建侧边菜单
  10. python调用函数出现未定义_在python中调用函数时出错“函数未定义”
  11. 李开复:中国创业有四大优势
  12. js随机选学员。从以下学员名单中随机选出4个学员。
  13. 全球最贵域名Sex.com将再度出售
  14. STM32三种BOOT模式
  15. 【软件质量】软件完整性
  16. MIR-Flickr25K数据集预处理
  17. HTML5七夕情人节表白网页(新年倒计时+白色雪花飘落) HTML+CSS+JS 求婚 html生日快乐祝福代码网页 520情人节告白代码 程序员表白源码 抖音3D旋转相册 js烟花代码 c
  18. 使用u盘PE安装原版xp系统
  19. 计算机Word如何删空行,绝招来了,一键删除Word文档中的空行、空格
  20. python画地球仪_Python pyecharts制作一个动态地球仪

热门文章

  1. 京娱meta哪里下载?怎么玩呢
  2. 免费一个彩虹屁机器人
  3. ios照片头信息的获取
  4. 2020年1月8日英雄联盟服务器多久维修,英雄联盟无限火力多久开启一次 2020无限火力开放时间表一览...
  5. Lipschitz函数
  6. c语言程序设计 出圈游戏,出圈游戏程序及设计.doc
  7. 为什么数据透视表不能分组_问题分组数据透视表项
  8. OpenCV检测圆并求出圆心与半径
  9. 从傅立叶级数到傅立叶变换
  10. linux 赚钱游戏服务器,在Linux上构建游戏服务器所需的一切