Java的文件操作太基礎(chǔ),缺乏很多實(shí)用工具,比如對(duì)目錄的操作,支持就非常的差了。如果你經(jīng)常用Java操作文件或文件夾,你會(huì)覺(jué)得反復(fù)編寫(xiě)這些代碼是令人沮喪的問(wèn)題,而且要大量用到遞歸。

    下面是的一個(gè)解決方案,借助Apache Commons IO工具包(commons-io-1.1.jar)來(lái)簡(jiǎn)單實(shí)現(xiàn)文件(夾)的復(fù)制、移動(dòng)、刪除、獲取大小等操作。

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

        /**
         * 復(fù)制文件或者目錄,復(fù)制前后文件完全一樣。
         *
         * @param resFilePath 源文件路徑
         * @param distFolder    目標(biāo)文件夾
         * @IOException 當(dāng)操作發(fā)生異常時(shí)拋出
         */
        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);
                }
        }

        /**
         * 刪除一個(gè)文件或者目錄
         *
         * @param targetPath 文件或者目錄路徑
         * @IOException 當(dāng)操作發(fā)生異常時(shí)拋出
         */
        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();
                }
        }

        /**
         * 移動(dòng)文件或者目錄,移動(dòng)前后文件完全一樣,如果目標(biāo)文件夾不存在則創(chuàng)建。
         *
         * @param resFilePath 源文件路徑
         * @param distFolder    目標(biāo)文件夾
         * @IOException 當(dāng)操作發(fā)生異常時(shí)拋出
         */
        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 操作成功標(biāo)識(shí)
         */
        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 目標(biāo)文件或者文件夾
         * @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;
        }

        /**
         * 判斷一個(gè)文件是否存在
         *
         * @param filePath 文件路徑
         * @return 存在返回true,否則返回false
         */
        public static boolean isExist(String filePath) {
                return new File(filePath).exists();
        }

        /**
         * 本地某個(gè)目錄下的文件列表(不遞歸)
         *
         * @param folder ftp上的某個(gè)目錄
         * @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);
        }

        /**
         * 將字符串寫(xiě)入指定文件(當(dāng)指定的父路徑中文件夾不存在時(shí),會(huì)最大限度去創(chuàng)建,以保證保存成功!)
         *
         * @param res            原字符串
         * @param filePath 文件路徑
         * @return 成功標(biāo)記
         */
        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];         //字符緩沖區(qū)
                        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 {
  /**
  * 將一個(gè)字符串的首字母改為大寫(xiě)或者小寫(xiě)
  *
  * @param srcString 源字符串
  * @param flag     大小寫(xiě)標(biāo)識(shí),ture小寫(xiě),false大些
  * @return 改寫(xiě)后的新字符串
  */
  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();
  }

  /**
  * 將一個(gè)字符串按照句點(diǎn)(.)分隔,返回最后一段
  *
  * @param clazzName 源字符串
  * @return 句點(diǎn)(.)分隔后的最后一段字符串
  */
  public static String getLastName(String clazzName) {
    String[] ls = clazzName.split("\\.");
    return ls[ls.length - 1];
  }

  /**
  * 格式化文件路徑,將其中不規(guī)范的分隔轉(zhuǎn)換為標(biāo)準(zhǔn)的分隔符,并且去掉末尾的"/"符號(hào)。
  *
  * @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;
  }

  /**
  * 格式化文件路徑,將其中不規(guī)范的分隔轉(zhuǎn)換為標(biāo)準(zhǔn)的分隔符,并且去掉末尾的"/"符號(hào)(適用于FTP遠(yuǎn)程文件路徑或者Web資源的相對(duì)路徑)。
  *
  * @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();
  }

  /**
  * 獲取相對(duì)路徑
  *
  * @param fullPath 全路徑
  * @param rootPath 根路徑
  * @return 相對(duì)根路徑的相對(duì)路徑
  */
  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("要處理的兩個(gè)字符串沒(méi)有包含關(guān)系,處理失敗!");
    }
    if (relativeRootPath == null) return null;
    else
        return formatPath(relativeRootPath);
  }

  /**
  * 獲取當(dāng)前系統(tǒng)換行符
  *
  * @return 系統(tǒng)換行符
  */
  public static String getSystemLineSeparator() {
    return System.getProperty("line.separator");
  }

  /**
  * 將用“|”分隔的字符串轉(zhuǎn)換為字符串集合列表,剔除分隔后各個(gè)字符串前后的空格
  *
  * @param series 將用“|”分隔的字符串
  * @return 字符串集合列表
  */
  public static List<String> series2List(String series) {
    return series2List(series, "\\|");
  }

  /**
  * 將用正則表達(dá)式regex分隔的字符串轉(zhuǎn)換為字符串集合列表,剔除分隔后各個(gè)字符串前后的空格
  *
  * @param series 用正則表達(dá)式分隔的字符串
  * @param regex 分隔串聯(lián)串的正則表達(dá)式
  * @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 通過(guò)“|”串聯(lián)為一個(gè)字符串
  */
  public static String list2series(List<String> strList) {
    StringBuffer series = new StringBuffer();
    for (String s : strList) {
        series.append(s).append("|");
    }
    return series.toString();
  }

  /**
  * 將字符串的首字母轉(zhuǎn)為小寫(xiě)
  *
  * @param resStr 源字符串
  * @return 首字母轉(zhuǎn)為小寫(xiě)后的字符串
  */
  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;
  }

  /**
  * 將字符串的首字母轉(zhuǎn)為大寫(xiě)
  *
  * @param resStr 源字符串
  * @return 首字母轉(zhuǎn)為大寫(xiě)后的字符串
  */
  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;
  }

}