我的日常

登录/注册
您现在的位置:论坛 资料库 JAVA开发 > Java File类总结和FileUtils类
总共48086条微博

动态微博

查看: 4727|回复: 0

Java File类总结和FileUtils类

[复制链接]
admin    

1244

主题

544

听众

1万

金钱

管理员

  • TA的每日心情

    2021-2-2 11:21
  • 签到天数: 36 天

    [LV.5]常住居民I

    管理员

    跳转到指定楼层
    楼主
    发表于 2015-04-23 09:04:20 |只看该作者 |倒序浏览
    文件存在和类型判断  创建出File类的对象并不代表该路径下有此文件或目录。
      用public boolean exists()可以判断文件是否存在。

      File类的对象可以是目录或者文件。
      如果是目录,public boolean isDirectory()返回true;
      如果是文件(非目录则是文件),public boolean isFile()返回true;
      但是注意需要先判断文件是否存在,如果文件不存在,上面两个方法都返回false,即不存在的File类对象既不是文件也不是目录

    创建文件  public boolean createNewFile()会创建一个新的空文件,只有该文件不存在的时候会创建,如果文件已经存在的话则返回false。
    创建文件夹  public boolean mkdir()
      创建目录,成功返回true。只能创建一个文件夹,要求所有的父目录都存在,否则创建失败。
      public boolean mkdirs()
      创建目录,成功返回true,会创建所有不存在的父目录。(注意即便最后创建失败,但是也可能创建了一些中间目录)。
      上面两个方法如果要创建的目录已经存在,不再重新创建,都返回false,只有新建目录返回true。

    目录操作  列出目录中的文件有以下方法可选:
      String[] list()
      String[] list(FilenameFilter filter)
      返回文件名数组。
      File[] listFiles()
      File[] listFiles(FileFilter filter)
      File[] listFiles(FilenameFilter filter)
      返回File数组。

      参数是文件或者文件名过滤器。

      注意返回为空和返回为null的意义是不同的。
      若不包含(符合条件的)文件,返回为空。
      但是如果返回为null,则表明调用方法的File对象可能不是一个目录,或者发生了IO错误。

    删除文件  boolean delete()方法会删除文件,如果File对象是文件则直接删除,对于目录来说,如果是空目录则直接删除,非空目录则无法删除,返回false。
      如果要删除的文件不能被删除则会抛出IOException。

      注意:不论是创建文件、创建目录还是删除文件,只有在动作真正发生的时候会返回true。

    FileUtils类  在项目中写一些工具类包装通用操作是很有必要的,看了一下apache的FileUtils类,copy了一些方法出来:
    1. /*
    2. * Licensed to the Apache Software Foundation (ASF) under one or more
    3. * contributor license agreements.  See the NOTICE file distributed with
    4. * this work for additional information regarding copyright ownership.
    5. * The ASF licenses this file to You under the Apache License, Version 2.0
    6. * (the "License"); you may not use this file except in compliance with
    7. * the License.  You may obtain a copy of the License at
    8. *
    9. *      http://www.apache.org/licenses/LICENSE-2.0
    10. *
    11. * Unless required by applicable law or agreed to in writing, software
    12. * distributed under the License is distributed on an "AS IS" BASIS,
    13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14. * See the License for the specific language governing permissions and
    15. * limitations under the License.
    16. */
    17. package com.mengdd.file;

    18. import java.io.File;
    19. import java.io.FileInputStream;
    20. import java.io.FileNotFoundException;
    21. import java.io.FileOutputStream;
    22. import java.io.IOException;

    23. /*
    24. * FileUtils copied from org.apache.commons.io.FileUtils
    25. */
    26. public class FileUtils {
    27.     /**
    28.      * Construct a file from the set of name elements.
    29.      *
    30.      * @param directory
    31.      *            the parent directory
    32.      * @param names
    33.      *            the name elements
    34.      * @return the file
    35.      */
    36.     public static File getFile(File directory, String... names) {
    37.         if (directory == null) {
    38.             throw new NullPointerException(
    39.                     "directorydirectory must not be null");
    40.         }
    41.         if (names == null) {
    42.             throw new NullPointerException("names must not be null");
    43.         }
    44.         File file = directory;
    45.         for (String name : names) {
    46.             file = new File(file, name);
    47.         }
    48.         return file;
    49.     }

    50.     /**
    51.      * Construct a file from the set of name elements.
    52.      *
    53.      * @param names
    54.      *            the name elements
    55.      * @return the file
    56.      */
    57.     public static File getFile(String... names) {
    58.         if (names == null) {
    59.             throw new NullPointerException("names must not be null");
    60.         }
    61.         File file = null;
    62.         for (String name : names) {
    63.             if (file == null) {
    64.                 file = new File(name);
    65.             }
    66.             else {
    67.                 file = new File(file, name);
    68.             }
    69.         }
    70.         return file;
    71.     }

    72.     /**
    73.      * Opens a {@link FileInputStream} for the specified file, providing better
    74.      * error messages than simply calling <code>new FileInputStream(file)</code>
    75.      * .
    76.      * <p>
    77.      * At the end of the method either the stream will be successfully opened,
    78.      * or an exception will have been thrown.
    79.      * <p>
    80.      * An exception is thrown if the file does not exist. An exception is thrown
    81.      * if the file object exists but is a directory. An exception is thrown if
    82.      * the file exists but cannot be read.
    83.      *
    84.      * @param file
    85.      *            the file to open for input, must not be {@code null}
    86.      * @return a new {@link FileInputStream} for the specified file
    87.      * @throws FileNotFoundException
    88.      *             if the file does not exist
    89.      * @throws IOException
    90.      *             if the file object is a directory
    91.      * @throws IOException
    92.      *             if the file cannot be read
    93.      */
    94.     public static FileInputStream openInputStream(File file) throws IOException {
    95.         if (file.exists()) {
    96.             if (file.isDirectory()) {
    97.                 throw new IOException("File '" + file
    98.                         + "' exists but is a directory");
    99.             }
    100.             if (file.canRead() == false) {
    101.                 throw new IOException("File '" + file + "' cannot be read");
    102.             }
    103.         }
    104.         else {
    105.             throw new FileNotFoundException("File '" + file
    106.                     + "' does not exist");
    107.         }
    108.         return new FileInputStream(file);
    109.     }

    110.     /**
    111.      * Opens a {@link FileOutputStream} for the specified file, checking and
    112.      * creating the parent directory if it does not exist.
    113.      * <p>
    114.      * At the end of the method either the stream will be successfully opened,
    115.      * or an exception will have been thrown.
    116.      * <p>
    117.      * The parent directory will be created if it does not exist. The file will
    118.      * be created if it does not exist. An exception is thrown if the file
    119.      * object exists but is a directory. An exception is thrown if the file
    120.      * exists but cannot be written to. An exception is thrown if the parent
    121.      * directory cannot be created.
    122.      *
    123.      * @param file
    124.      *            the file to open for output, must not be {@code null}
    125.      * @param append
    126.      *            if {@code true}, then bytes will be added to the
    127.      *            end of the file rather than overwriting
    128.      * @return a new {@link FileOutputStream} for the specified file
    129.      * @throws IOException
    130.      *             if the file object is a directory
    131.      * @throws IOException
    132.      *             if the file cannot be written to
    133.      * @throws IOException
    134.      *             if a parent directory needs creating but that fails
    135.      */
    136.     public static FileOutputStream openOutputStream(File file, boolean append)
    137.             throws IOException {
    138.         if (file.exists()) {
    139.             if (file.isDirectory()) {
    140.                 throw new IOException("File '" + file
    141.                         + "' exists but is a directory");
    142.             }
    143.             if (file.canWrite() == false) {
    144.                 throw new IOException("File '" + file
    145.                         + "' cannot be written to");
    146.             }
    147.         }
    148.         else {
    149.             File parent = file.getParentFile();
    150.             if (parent != null) {
    151.                 if (!parent.mkdirs() && !parent.isDirectory()) {
    152.                     throw new IOException("Directory '" + parent
    153.                             + "' could not be created");
    154.                 }
    155.             }
    156.         }
    157.         return new FileOutputStream(file, append);
    158.     }

    159.     public static FileOutputStream openOutputStream(File file)
    160.             throws IOException {
    161.         return openOutputStream(file, false);
    162.     }

    163.     /**
    164.      * Cleans a directory without deleting it.
    165.      *
    166.      * @param directory
    167.      *            directory to clean
    168.      * @throws IOException
    169.      *             in case cleaning is unsuccessful
    170.      */
    171.     public static void cleanDirectory(File directory) throws IOException {
    172.         if (!directory.exists()) {
    173.             String message = directory + " does not exist";
    174.             throw new IllegalArgumentException(message);
    175.         }

    176.         if (!directory.isDirectory()) {
    177.             String message = directory + " is not a directory";
    178.             throw new IllegalArgumentException(message);
    179.         }

    180.         File[] files = directory.listFiles();
    181.         if (files == null) { // null if security restricted
    182.             throw new IOException("Failed to list contents of " + directory);
    183.         }

    184.         IOException exception = null;
    185.         for (File file : files) {
    186.             try {
    187.                 forceDelete(file);
    188.             }
    189.             catch (IOException ioe) {
    190.                 exception = ioe;
    191.             }
    192.         }

    193.         if (null != exception) {
    194.             throw exception;
    195.         }
    196.     }

    197.     // -----------------------------------------------------------------------
    198.     /**
    199.      * Deletes a directory recursively.
    200.      *
    201.      * @param directory
    202.      *            directory to delete
    203.      * @throws IOException
    204.      *             in case deletion is unsuccessful
    205.      */
    206.     public static void deleteDirectory(File directory) throws IOException {
    207.         if (!directory.exists()) {
    208.             return;
    209.         }

    210.         cleanDirectory(directory);

    211.         if (!directory.delete()) {
    212.             String message = "Unable to delete directory " + directory + ".";
    213.             throw new IOException(message);
    214.         }
    215.     }

    216.     /**
    217.      * Deletes a file. If file is a directory, delete it and all
    218.      * sub-directories.
    219.      * <p>
    220.      * The difference between File.delete() and this method are:
    221.      * <ul>
    222.      * <li>A directory to be deleted does not have to be empty.</li>
    223.      * <li>You get exceptions when a file or directory cannot be deleted.
    224.      * (java.io.File methods returns a boolean)</li>
    225.      * </ul>
    226.      *
    227.      * @param file
    228.      *            file or directory to delete, must not be {@code null}
    229.      * @throws NullPointerException
    230.      *             if the directory is {@code null}
    231.      * @throws FileNotFoundException
    232.      *             if the file was not found
    233.      * @throws IOException
    234.      *             in case deletion is unsuccessful
    235.      */
    236.     public static void forceDelete(File file) throws IOException {
    237.         if (file.isDirectory()) {
    238.             deleteDirectory(file);
    239.         }
    240.         else {
    241.             boolean filePresent = file.exists();
    242.             if (!file.delete()) {
    243.                 if (!filePresent) {
    244.                     throw new FileNotFoundException("File does not exist: "
    245.                             + file);
    246.                 }
    247.                 String message = "Unable to delete file: " + file;
    248.                 throw new IOException(message);
    249.             }
    250.         }
    251.     }

    252.     /**
    253.      * Deletes a file, never throwing an exception. If file is a directory,
    254.      * delete it and all sub-directories.
    255.      * <p>
    256.      * The difference between File.delete() and this method are:
    257.      * <ul>
    258.      * <li>A directory to be deleted does not have to be empty.</li>
    259.      * <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
    260.      * </ul>
    261.      *
    262.      * @param file
    263.      *            file or directory to delete, can be {@code null}
    264.      * @return {@code true} if the file or directory was deleted, otherwise
    265.      *         {@code false}
    266.      *
    267.      */
    268.     public static boolean deleteQuietly(File file) {
    269.         if (file == null) {
    270.             return false;
    271.         }
    272.         try {
    273.             if (file.isDirectory()) {
    274.                 cleanDirectory(file);
    275.             }
    276.         }
    277.         catch (Exception ignored) {
    278.         }

    279.         try {
    280.             return file.delete();
    281.         }
    282.         catch (Exception ignored) {
    283.             return false;
    284.         }
    285.     }

    286.     /**
    287.      * Makes a directory, including any necessary but nonexistent parent
    288.      * directories. If a file already exists with specified name but it is
    289.      * not a directory then an IOException is thrown.
    290.      * If the directory cannot be created (or does not already exist)
    291.      * then an IOException is thrown.
    292.      *
    293.      * @param directory
    294.      *            directory to create, must not be {@code null}
    295.      * @throws NullPointerException
    296.      *             if the directory is {@code null}
    297.      * @throws IOException
    298.      *             if the directory cannot be created or the file already exists
    299.      *             but is not a directory
    300.      */
    301.     public static void forceMkdir(File directory) throws IOException {
    302.         if (directory.exists()) {
    303.             if (!directory.isDirectory()) {
    304.                 String message = "File " + directory + " exists and is "
    305.                         + "not a directory. Unable to create directory.";
    306.                 throw new IOException(message);
    307.             }
    308.         }
    309.         else {
    310.             if (!directory.mkdirs()) {
    311.                 // Double-check that some other thread or process hasn't made
    312.                 // the directory in the background
    313.                 if (!directory.isDirectory()) {
    314.                     String message = "Unable to create directory " + directory;
    315.                     throw new IOException(message);
    316.                 }
    317.             }
    318.         }
    319.     }

    320.     /**
    321.      * Returns the size of the specified file or directory. If the provided
    322.      * {@link File} is a regular file, then the file's length is returned.
    323.      * If the argument is a directory, then the size of the directory is
    324.      * calculated recursively. If a directory or subdirectory is security
    325.      * restricted, its size will not be included.
    326.      *
    327.      * @param file
    328.      *            the regular file or directory to return the size
    329.      *            of (must not be {@code null}).
    330.      *
    331.      * @return the length of the file, or recursive size of the directory,
    332.      *         provided (in bytes).
    333.      *
    334.      * @throws NullPointerException
    335.      *             if the file is {@code null}
    336.      * @throws IllegalArgumentException
    337.      *             if the file does not exist.
    338.      *
    339.      */
    340.     public static long sizeOf(File file) {

    341.         if (!file.exists()) {
    342.             String message = file + " does not exist";
    343.             throw new IllegalArgumentException(message);
    344.         }

    345.         if (file.isDirectory()) {
    346.             return sizeOfDirectory(file);
    347.         }
    348.         else {
    349.             return file.length();
    350.         }

    351.     }

    352.     /**
    353.      * Counts the size of a directory recursively (sum of the length of all
    354.      * files).
    355.      *
    356.      * @param directory
    357.      *            directory to inspect, must not be {@code null}
    358.      * @return size of directory in bytes, 0 if directory is security
    359.      *         restricted, a negative number when the real total
    360.      *         is greater than {@link Long#MAX_VALUE}.
    361.      * @throws NullPointerException
    362.      *             if the directory is {@code null}
    363.      */
    364.     public static long sizeOfDirectory(File directory) {
    365.         checkDirectory(directory);

    366.         final File[] files = directory.listFiles();
    367.         if (files == null) { // null if security restricted
    368.             return 0L;
    369.         }
    370.         long size = 0;

    371.         for (final File file : files) {

    372.             size += sizeOf(file);
    373.             if (size < 0) {
    374.                 break;

    375.             }

    376.         }

    377.         return size;
    378.     }

    379.     /**
    380.      * Checks that the given {@code File} exists and is a directory.
    381.      *
    382.      * @param directory
    383.      *            The {@code File} to check.
    384.      * @throws IllegalArgumentException
    385.      *             if the given {@code File} does not exist or is not a
    386.      *             directory.
    387.      */
    388.     private static void checkDirectory(File directory) {
    389.         if (!directory.exists()) {
    390.             throw new IllegalArgumentException(directory + " does not exist");
    391.         }
    392.         if (!directory.isDirectory()) {
    393.             throw new IllegalArgumentException(directory
    394.                     + " is not a directory");
    395.         }
    396.     }

    397. }

    398. FileUtils.java
    复制代码

    参考资料  File类官方文档:
      http://docs.oracle.com/javase/7/docs/api/java/io/File.html
      org.apache.commons.io.FileUtils源码
      http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/2.4/org/apache/commons/io/FileUtils.java




    科帮网 1、本主题所有言论和图片纯属会员个人意见,与本社区立场无关
    2、本站所有主题由该帖子作者发表,该帖子作者与科帮网享有帖子相关版权
    3、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者和科帮网的同意
    4、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任
    5、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责
    6、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意
    7、科帮网管理员和版主有权不事先通知发贴者而删除本文


    JAVA爱好者①群:JAVA爱好者① JAVA爱好者②群:JAVA爱好者② JAVA爱好者③ : JAVA爱好者③

    本帖被以下淘专辑推荐:

    红红火火恍恍惚惚
    快速回复
    您需要登录后才可以回帖 登录 | 立即注册

       

    关闭

    站长推荐上一条 /1 下一条

    发布主题 快速回复 返回列表 联系我们 官方QQ群 科帮网手机客户端
    快速回复 返回顶部 返回列表