zoukankan      html  css  js  c++  java
  • apache的FileUtils方法大全

    FileUtils

    获取系统的临时目录路径:getTempDirectoryPath()

     

    1. public static String getTempDirectoryPath() {  
    2.   
    3.            return System.getProperty("java.io.tmpdir");  
    4.   
    5.  }  

     

     

    获取代表系统临时目录的文件:getTempDirectory ()

     

    1. public static File getTempDirectory() {  
    2.   
    3.            return new File(getTempDirectoryPath());  
    4.   
    5.  }  

     

     

    获取用户的主目录路径:getUserDirectoryPath()

     

    1. public static String getUserDirectoryPath() {  
    2.   
    3.            return System.getProperty("user.home");  
    4.   
    5.  }  

     

     

    获取代表用户主目录的文件:getUserDirectory()

     

    1. public static File getUserDirectory() {  
    2.   
    3.            return new File(getUserDirectoryPath());  
    4.   
    5. }  

     

     

    根据指定的文件获取一个新的文件输入流:openInputStream(File file)

     

    1. public static FileInputStream openInputStream(File file) throws IOException {  
    2.   
    3.            if (file.exists()) {  
    4.   
    5.                if (file.isDirectory()) {  
    6.   
    7.                    throw new IOException("File '" + file + "' exists but is adirectory");  
    8.   
    9.                }  
    10.   
    11.                if (file.canRead() == false) {  
    12.   
    13.                    throw new IOException("File '" + file + "' cannot be read");  
    14.   
    15.                }  
    16.   
    17.            } else {  
    18.   
    19.                throw newFileNotFoundException("File '" + file + "' does notexist");  
    20.   
    21.            }  
    22.   
    23.            return new FileInputStream(file);  
    24.   
    25.        }  

     

     

    根据指定的文件获取一个新的文件输出流:openOutputStream (File file)

     

    1. public static FileOutputStream openOutputStream(File file) throws IOException {  
    2.   
    3.            if (file.exists()) {  
    4.   
    5.                if (file.isDirectory()) {  
    6.   
    7.                    throw new IOException("File'" + file + "' exists but is a directory");  
    8.   
    9.                }  
    10.   
    11.                if (file.canWrite() == false) {  
    12.   
    13.                    throw new IOException("File '" + file + "' cannot be written to");  
    14.   
    15.                }  
    16.   
    17.            } else {  
    18.   
    19.                File parent = file.getParentFile();  
    20.   
    21.                if (parent != null &&parent.exists() == false) {  
    22.   
    23.                    if (parent.mkdirs() ==false) {  
    24.   
    25.                        throw new IOException("File '" + file + "' could not be created");  
    26.   
    27.                    }  
    28.   
    29.                }  
    30.   
    31.            }  
    32.   
    33.            return new FileOutputStream(file);  
    34.   
    35.        }  

     

     

    字节转换成直观带单位的值(包括单位GB,MB,KB或字节)byteCountToDisplaySize(long size)

     

    1. public static StringbyteCountToDisplaySize(long size) {  
    2.   
    3.           String displaySize;  
    4.   
    5.           if (size / ONE_GB > 0) {  
    6.   
    7.               displaySize =String.valueOf(size / ONE_GB) + " GB";  
    8.   
    9.           } else if (size / ONE_MB > 0) {  
    10.   
    11.               displaySize =String.valueOf(size / ONE_MB) + " MB";  
    12.   
    13.           } else if (size / ONE_KB > 0) {  
    14.   
    15.               displaySize =String.valueOf(size / ONE_KB) + " KB";  
    16.   
    17.           } else {  
    18.   
    19.               displaySize =String.valueOf(size) + " bytes";  
    20.   
    21.           }  
    22.   
    23.           return displaySize;  
    24.   
    25.       }  

     

     

    创建一个空文件,若文件应经存在则只更改文件的最近修改时间:touch(File file)

    1. public static void touch(File file) throws IOException {  
    2.   
    3.          if (!file.exists()) {  
    4.   
    5.              OutputStream out =openOutputStream(file);  
    6.   
    7.              IOUtils.closeQuietly(out);  
    8.   
    9.          }  
    10.   
    11.          boolean success =file.setLastModified(System.currentTimeMillis());  
    12.   
    13.          if (!success) {  
    14.   
    15.              throw new IOException("Unableto set the last modification time for " + file);  
    16.   
    17.          }  
    18.   
    19.      }  



    把相应的文件集合转换成文件数组convertFileCollectionToFileArray(Collection<File> files)

    1. public static File[] convertFileCollectionToFileArray(Collection<File> files) {  
    2.   
    3.             return files.toArray(newFile[files.size()]);  
    4.   
    5.        }  



    根据一个过滤规则获取一个目录下的文件innerListFiles(Collection<File> files, File directory,IOFileFilterfilter)

    1. private static void innerListFiles(Collection<File> files, File directory,  
    2.   
    3.                IOFileFilter filter) {  
    4.   
    5.            File[] found =directory.listFiles((FileFilter) filter);  
    6.   
    7.            if (found != null) {  
    8.   
    9.                for (File file : found) {  
    10.   
    11.                    if (file.isDirectory()) {  
    12.   
    13.                        innerListFiles(files,file, filter);  
    14.   
    15.                    } else {  
    16.   
    17.                        files.add(file);  
    18.   
    19.                    }  
    20.   
    21.                }  
    22.   
    23.            }  
    24.   
    25.        }  



    根据一个IOFileFilter过滤规则获取一个目录下的文件集合listFiles( File directory, IOFileFilterfileFilter, IOFileFilter dirFilter)

    1. public static Collection<File> listFiles(  
    2.   
    3.                File directory, IOFileFilterfileFilter, IOFileFilter dirFilter) {  
    4.   
    5.            if (!directory.isDirectory()) {  
    6.   
    7.                throw newIllegalArgumentException(  
    8.   
    9.                        "Parameter'directory' is not a directory");  
    10.   
    11.            }  
    12.   
    13.            if (fileFilter == null) {  
    14.   
    15.                throw newNullPointerException("Parameter 'fileFilter' is null");  
    16.   
    17.            }  
    18.   
    19.     
    20.   
    21.            //Setup effective file filter  
    22.   
    23.            IOFileFilter effFileFilter =FileFilterUtils.and(fileFilter,  
    24.   
    25.                FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));  
    26.   
    27.     
    28.   
    29.            //Setup effective directory filter  
    30.   
    31.            IOFileFilter effDirFilter;  
    32.   
    33.            if (dirFilter == null) {  
    34.   
    35.                effDirFilter =FalseFileFilter.INSTANCE;  
    36.   
    37.            } else {  
    38.   
    39.                effDirFilter =FileFilterUtils.and(dirFilter,  
    40.   
    41.                   DirectoryFileFilter.INSTANCE);  
    42.   
    43.            }  
    44.   
    45.     
    46.   
    47.            //Find files  
    48.   
    49.            Collection<File> files = newjava.util.LinkedList<File>();  
    50.   
    51.            innerListFiles(files, directory,  
    52.   
    53.               FileFilterUtils.or(effFileFilter, effDirFilter));  
    54.   
    55.            return files;  
    56.   
    57.        }  



    根据一个IOFileFilter过滤规则获取一个目录下的文件集合的Iterator迭代器iterateFiles( File directory, IOFileFilterfileFilter, IOFileFilter dirFilter)

    1. public static Iterator<File> iterateFiles( File directory, IOFileFilterfileFilter, IOFileFilter dirFilter) {  
    2.   
    3.       return listFiles(directory,fileFilter, dirFilter).iterator();  
    4.   
    5.   }  



    把指定的字符串数组变成后缀名格式字符串数组toSuffixes(String[] extensions)

    1. private static String[] toSuffixes(String[] extensions) {  
    2.   
    3.            String[] suffixes = new String[extensions.length];  
    4.   
    5.            for (int i = 0; i <extensions.length; i++) {  
    6.   
    7.                suffixes[i] = "." +extensions[i];  
    8.   
    9.            }  
    10.   
    11.            return suffixes;  
    12.   
    13.        }  



    查找一个目录下面符合对应扩展名的文件的集合listFiles(File directory, String[]extensions, boolean recursive)

     

    1. public static Collection<File> listFiles( File directory, String[]extensions, boolean recursive) {  
    2.   
    3.            IOFileFilter filter;  
    4.   
    5.            if (extensions == null) {  
    6.   
    7.                filter =TrueFileFilter.INSTANCE;  
    8.   
    9.            } else {  
    10.   
    11.                String[] suffixes =toSuffixes(extensions);  
    12.   
    13.                filter = newSuffixFileFilter(suffixes);  
    14.   
    15.            }  
    16.   
    17.            return listFiles(directory, filter,  
    18.   
    19.                (recursive ?TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE));  
    20.   
    21.        }  

     

     

    查找一个目录下面符合对应扩展名的文件的集合的迭代器Iterator<File> iterateFiles( File directory, String[]extensions, boolean recursive)

    1. public static Iterator<File> iterateFiles( File directory, String[]extensions, boolean recursive) {  
    2.   
    3.            return listFiles(directory,extensions, recursive).iterator();  
    4.   
    5.        }  



    判断两个文件是否相等contentEquals(Filefile1, File file2)

    1. public static boolean contentEquals(File file1, File file2) throws IOException {  
    2.   
    3.            boolean file1Exists =file1.exists();  
    4.   
    5.            if (file1Exists != file2.exists()) {  
    6.   
    7.                return false;  
    8.   
    9.            }  
    10.   
    11.     
    12.   
    13.            if (!file1Exists) {  
    14.   
    15.                // two not existing files areequal  
    16.   
    17.                return true;  
    18.   
    19.            }  
    20.   
    21.     
    22.   
    23.            if (file1.isDirectory() ||file2.isDirectory()) {  
    24.   
    25.                // don't want to comparedirectory contents  
    26.   
    27.                throw new IOException("Can't compare directories, only files");  
    28.   
    29.            }  
    30.   
    31.     
    32.   
    33.            if (file1.length() !=file2.length()) {  
    34.   
    35.                // lengths differ, cannot beequal  
    36.   
    37.                return false;  
    38.   
    39.            }  
    40.   
    41.     
    42.   
    43.            if(file1.getCanonicalFile().equals(file2.getCanonicalFile())) {  
    44.   
    45.                // same file  
    46.   
    47.                return true;  
    48.   
    49.            }  
    50.   
    51.     
    52.   
    53.            InputStream input1 = null;  
    54.   
    55.            InputStream input2 = null;  
    56.   
    57.            try {  
    58.   
    59.                input1 = newFileInputStream(file1);  
    60.   
    61.                input2 = newFileInputStream(file2);  
    62.   
    63.                returnIOUtils.contentEquals(input1, input2);  
    64.   
    65.     
    66.   
    67.            } finally {  
    68.   
    69.                IOUtils.closeQuietly(input1);  
    70.   
    71.                IOUtils.closeQuietly(input2);  
    72.   
    73.            }  
    74.   
    75.        }  



    根据一个Url来创建一个文件toFile(URL url)

    1. public static File toFile(URL url) {  
    2.   
    3.            if (url == null ||!"file".equalsIgnoreCase(url.getProtocol())) {  
    4.   
    5.                return null;  
    6.   
    7.            } else {  
    8.   
    9.                String filename =url.getFile().replace('/', File.separatorChar);  
    10.   
    11.                filename = decodeUrl(filename);  
    12.   
    13.                return new File(filename);  
    14.   
    15.            }  
    16.   
    17.        }  



     

    对一个Url字符串进行将指定的URL按照RFC 3986进行转换decodeUrl(Stringurl)

    1. static String decodeUrl(String url) {  
    2.   
    3.            String decoded = url;  
    4.   
    5.            if (url != null &&url.indexOf('%') >= 0) {  
    6.   
    7.                int n = url.length();  
    8.   
    9.                StringBuffer buffer = newStringBuffer();  
    10.   
    11.                ByteBuffer bytes =ByteBuffer.allocate(n);  
    12.   
    13.                for (int i = 0; i < n;) {  
    14.   
    15.                    if (url.charAt(i) == '%') {  
    16.   
    17.                        try {  
    18.   
    19.                            do {  
    20.   
    21.                                byte octet =(byte) Integer.parseInt(url.substring(i + 1, i + 3), 16);  
    22.   
    23.                               bytes.put(octet);  
    24.   
    25.                                i += 3;  
    26.   
    27.                            } while (i < n&& url.charAt(i) == '%');  
    28.   
    29.                            continue;  
    30.   
    31.                        } catch(RuntimeException e) {  
    32.   
    33.                            // malformedpercent-encoded octet, fall through and  
    34.   
    35.                            // append charactersliterally  
    36.   
    37.                        } finally {  
    38.   
    39.                            if (bytes.position()> 0) {  
    40.   
    41.                                bytes.flip();  
    42.   
    43.                               buffer.append(UTF8.decode(bytes).toString());  
    44.   
    45.                                bytes.clear();  
    46.   
    47.                            }  
    48.   
    49.                        }  
    50.   
    51.                    }  
    52.   
    53.                   buffer.append(url.charAt(i++));  
    54.   
    55.                }  
    56.   
    57.                decoded = buffer.toString();  
    58.   
    59.            }  
    60.   
    61.            return decoded;  
    62.   
    63.        }  



    将一个URL数组转化成一个文件数组toFiles(URL[] urls)

    1. public static File[]  toFiles(URL[] urls) {  
    2.   
    3.            if (urls == null || urls.length ==0) {  
    4.   
    5.                return EMPTY_FILE_ARRAY;  
    6.   
    7.            }  
    8.   
    9.            File[] files = newFile[urls.length];  
    10.   
    11.            for (int i = 0; i < urls.length;i++) {  
    12.   
    13.                URL url = urls[i];  
    14.   
    15.                if (url != null) {  
    16.   
    17.                    if(url.getProtocol().equals("file") == false) {  
    18.   
    19.                        throw newIllegalArgumentException(  
    20.   
    21.                                "URL couldnot be converted to a File: " + url);  
    22.   
    23.                    }  
    24.   
    25.                    files[i] = toFile(url);  
    26.   
    27.                }  
    28.   
    29.            }  
    30.   
    31.            return files;  
    32.   
    33.        }  



    将一个文件数组转化成一个URL数组toURLs(File[] files)

     

    1. public static URL[]   toURLs(File[] files)throws IOException {  
    2.   
    3.           URL[] urls = new URL[files.length];  
    4.   
    5.    
    6.   
    7.           for (int i = 0; i < urls.length;i++) {  
    8.   
    9.               urls[i] =files[i].toURI().toURL();  
    10.   
    11.           }  
    12.   
    13.    
    14.   
    15.           return urls;  
    16.   
    17.       }  



     

    拷贝一个文件到指定的目录文件copyFileToDirectory(File srcFile, File destDir)

    1. public static void copyFileToDirectory(File srcFile, File destDir) throws IOException{  
    2.   
    3.            copyFileToDirectory(srcFile,destDir, true);  
    4.   
    5.        }  



    拷贝一个文件到指定的目录文件并且设置是否更新文件的最近修改时间copyFileToDirectory(File srcFile, File destDir, booleanpreserveFileDate)

    1. public static void copyFileToDirectory(File srcFile, File destDir, booleanpreserveFileDate) throws IOException {  
    2.   
    3.            if (destDir == null) {  
    4.   
    5.                throw new NullPointerException("Destination must not be null");  
    6.   
    7.            }  
    8.   
    9.            if (destDir.exists() &&destDir.isDirectory() == false) {  
    10.   
    11.                throw new IllegalArgumentException("Destination '" + destDir + "' is not adirectory");  
    12.   
    13.            }  
    14.   
    15.            File destFile = new File(destDir,srcFile.getName());  
    16.   
    17.            copyFile(srcFile, destFile,preserveFileDate);  
    18.   
    19.        }  



    拷贝文件到新的文件中并且保存最近修改时间copyFile(File srcFile, File destFile)

    1. public static void copyFile(File srcFile, File destFile) throws IOException {  
    2.   
    3.            copyFile(srcFile, destFile, true);  
    4.   
    5.        }  



    拷贝文件到新的文件中并且设置是否保存最近修改时间copyFile(File srcFile, File destFile,boolean preserveFileDate)

    1. public static void copyFile(File srcFile, File destFile,boolean preserveFileDate) throwsIOException {  
    2.   
    3.            if (srcFile == null) {  
    4.   
    5.                throw new NullPointerException("Source must not be null");  
    6.   
    7.            }  
    8.   
    9.            if (destFile == null) {  
    10.   
    11.                throw new NullPointerException("Destination must not be null");  
    12.   
    13.            }  
    14.   
    15.            if (srcFile.exists() == false) {  
    16.   
    17.                throw new FileNotFoundException("Source '" + srcFile + "' does notexist");  
    18.   
    19.            }  
    20.   
    21.            if (srcFile.isDirectory()) {  
    22.   
    23.                throw new IOException("Source '" + srcFile + "' exists but is adirectory");  
    24.   
    25.            }  
    26.   
    27.            if(srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {  
    28.   
    29.                throw new IOException("Source '" + srcFile + "' and destination '" +destFile + "' are the same");  
    30.   
    31.            }  
    32.   
    33.            if (destFile.getParentFile() != null&& destFile.getParentFile().exists() == false) {  
    34.   
    35.                if(destFile.getParentFile().mkdirs() == false) {  
    36.   
    37.                    throw new IOException("Destination '" + destFile + "' directory cannot becreated");  
    38.   
    39.                }  
    40.   
    41.            }  
    42.   
    43.            if (destFile.exists() &&destFile.canWrite() == false) {  
    44.   
    45.                throw new IOException("Destination '" + destFile + "' exists but isread-only");  
    46.   
    47.            }  
    48.   
    49.            doCopyFile(srcFile, destFile,preserveFileDate);  
    50.   
    51.        }  



    拷贝文件到新的文件中并且设置是否保存最近修改时间doCopyFile(File srcFile, File destFile, boolean preserveFileDate)

     

    1. private static void doCopyFile(File srcFile,File destFile, boolean preserveFileDate) throws IOException {  
    2.   
    3.           if (destFile.exists() &&destFile.isDirectory()) {  
    4.   
    5.               throw new IOException("Destination '" + destFile + "' exists but is adirectory");  
    6.   
    7.           }  
    8.   
    9.    
    10.   
    11.           FileInputStream fis = null;  
    12.   
    13.           FileOutputStream fos = null;  
    14.   
    15.           FileChannel input = null;  
    16.   
    17.           FileChannel output = null;  
    18.   
    19.           try {  
    20.   
    21.               fis = newFileInputStream(srcFile);  
    22.   
    23.               fos = newFileOutputStream(destFile);  
    24.   
    25.               input  = fis.getChannel();  
    26.   
    27.               output = fos.getChannel();  
    28.   
    29.               long size = input.size();  
    30.   
    31.               long pos = 0;  
    32.   
    33.               long count = 0;  
    34.   
    35.               while (pos < size) {  
    36.   
    37.                   count = (size - pos) >FIFTY_MB ? FIFTY_MB : (size - pos);  
    38.   
    39.                   pos +=output.transferFrom(input, pos, count);  
    40.   
    41.               }  
    42.   
    43.           } finally {  
    44.   
    45.               IOUtils.closeQuietly(output);  
    46.   
    47.               IOUtils.closeQuietly(fos);  
    48.   
    49.               IOUtils.closeQuietly(input);  
    50.   
    51.               IOUtils.closeQuietly(fis);  
    52.   
    53.           }  
    54.   
    55.    
    56.   
    57.           if (srcFile.length() !=destFile.length()) {  
    58.   
    59.               throw new IOException("Failed to copy full contents from '" +  
    60.   
    61.                       srcFile + "' to '"+ destFile + "'");  
    62.   
    63.           }  
    64.   
    65.           if (preserveFileDate) {  
    66.   
    67.              destFile.setLastModified(srcFile.lastModified());  
    68.   
    69.           }  
    70.   
    71.       }  

     

     

    将一个目录拷贝到另一目录中,并且保存最近更新时间copyDirectoryToDirectory(File srcDir, File destDir)

    1. public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException {  
    2.   
    3.            if (srcDir == null) {  
    4.   
    5.                throw new NullPointerException("Source must not be null");  
    6.   
    7.            }  
    8.   
    9.            if (srcDir.exists() &&srcDir.isDirectory() == false) {  
    10.   
    11.                throw new IllegalArgumentException("Source'" + destDir + "' is not a directory");  
    12.   
    13.            }  
    14.   
    15.            if (destDir == null) {  
    16.   
    17.                throw new NullPointerException("Destination must not be null");  
    18.   
    19.            }  
    20.   
    21.            if (destDir.exists() &&destDir.isDirectory() == false) {  
    22.   
    23.                throw new IllegalArgumentException("Destination '" + destDir + "' is not adirectory");  
    24.   
    25.            }  
    26.   
    27.            copyDirectory(srcDir, newFile(destDir, srcDir.getName()), true);  
    28.   
    29.        }  



    拷贝整个目录到新的位置,并且保存最近修改时间copyDirectory(File srcDir, File destDir)

    1. public static void copyDirectory(File srcDir, File destDir) throws IOException{  
    2.   
    3.          copyDirectory(srcDir, destDir,true);  
    4.   
    5.      }  



    拷贝整个目录到新的位置,并且设置是否保存最近修改时间copyDirectory(File srcDir, File destDir, boolean preserveFileDate)

    1. public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException {  
    2.   
    3.            copyDirectory(srcDir, destDir, null,preserveFileDate);  
    4.   
    5.        }  



    拷贝过滤后的目录到指定的位置,并且保存最近修改时间copyDirectory(File srcDir, File destDir, FileFilter filter)

    1. public static void copyDirectory(File srcDir, File destDir, FileFilter filter) throws IOException {  
    2.   
    3.            copyDirectory(srcDir, destDir,filter, true);  
    4.   
    5.        }  



    拷贝过滤后的目录到指定的位置,并且设置是否保存最近修改时间copyDirectory(File srcDir, File destDir,FileFilter filter, booleanpreserveFileDate)

    1. public static void copyDirectory(File srcDir, File destDir,FileFilter filter, booleanpreserveFileDate) throws IOException {  
    2.   
    3.             if (srcDir == null) {  
    4.   
    5.                 throw new NullPointerException("Source must not be null");  
    6.   
    7.             }  
    8.   
    9.             if (destDir == null) {  
    10.   
    11.                 throw new NullPointerException("Destination must not be null");  
    12.   
    13.             }  
    14.   
    15.             if (srcDir.exists() == false) {  
    16.   
    17.                 throw new FileNotFoundException("Source '" + srcDir + "' does notexist");  
    18.   
    19.             }  
    20.   
    21.             if (srcDir.isDirectory() == false){  
    22.   
    23.                 throw new IOException("Source '" + srcDir + "' exists but is not adirectory");  
    24.   
    25.             }  
    26.   
    27.             if(srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {  
    28.   
    29.                 throw new IOException("Source '" + srcDir + "' and destination '" +destDir + "' are the same");  
    30.   
    31.             }  
    32.   
    33.      
    34.   
    35.             // Cater for destination being directorywithin the source directory (see IO-141)  
    36.   
    37.             List<String> exclusionList =null;  
    38.   
    39.             if(destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {  
    40.   
    41.                 File[] srcFiles = filter ==null ? srcDir.listFiles() : srcDir.listFiles(filter);  
    42.   
    43.                 if (srcFiles != null &&srcFiles.length > 0) {  
    44.   
    45.                     exclusionList = newArrayList<String>(srcFiles.length);  
    46.   
    47.                     for (File srcFile :srcFiles) {  
    48.   
    49.                         File copiedFile = new File(destDir, srcFile.getName());  
    50.   
    51.                        exclusionList.add(copiedFile.getCanonicalPath());  
    52.   
    53.                     }  
    54.   
    55.                 }  
    56.   
    57.             }  
    58.   
    59.             doCopyDirectory(srcDir, destDir,filter, preserveFileDate, exclusionList);  
    60.   
    61.         }  



    内部拷贝目录的方法doCopyDirectory(FilesrcDir, File destDir, FileFilter filter, boolean preserveFileDate,List<String> exclusionList)

    1. private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter,boolean preserveFileDate,List<String> exclusionList) throws IOException {  
    2.   
    3.             // recurse  
    4.   
    5.             File[] files = filter == null ?srcDir.listFiles() : srcDir.listFiles(filter);  
    6.   
    7.             if (files == null) {  // null if security restricted  
    8.   
    9.                 throw new IOException("Failed to list contents of " + srcDir);  
    10.   
    11.             }  
    12.   
    13.             if (destDir.exists()) {  
    14.   
    15.                 if (destDir.isDirectory() ==false) {  
    16.   
    17.                     throw new IOException("Destination '" + destDir + "' exists but is not adirectory");  
    18.   
    19.                 }  
    20.   
    21.             } else {  
    22.   
    23.                 if (destDir.mkdirs() == false){  
    24.   
    25.                     throw new IOException("Destination '" + destDir + "' directory cannot becreated");  
    26.   
    27.                 }  
    28.   
    29.             }  
    30.   
    31.             if (destDir.canWrite() == false) {  
    32.   
    33.                 throw new IOException("Destination '" + destDir + "' cannot be writtento");  
    34.   
    35.             }  
    36.   
    37.             for (File file : files) {  
    38.   
    39.                 File copiedFile = newFile(destDir, file.getName());  
    40.   
    41.                 if (exclusionList == null ||!exclusionList.contains(file.getCanonicalPath())) {  
    42.   
    43.                     if (file.isDirectory()) {  
    44.   
    45.                         doCopyDirectory(file,copiedFile, filter, preserveFileDate, exclusionList);  
    46.   
    47.                     } else {  
    48.   
    49.                         doCopyFile(file,copiedFile, preserveFileDate);  
    50.   
    51.                     }  
    52.   
    53.                 }  
    54.   
    55.             }  
    56.   
    57.      
    58.   
    59.             // Do this last, as the above hasprobably affected directory metadata  
    60.   
    61.             if (preserveFileDate) {  
    62.   
    63.                destDir.setLastModified(srcDir.lastModified());  
    64.   
    65.             }  
    66.   
    67.         }  



    根据一个Url拷贝字节到一个文件中copyURLToFile(URL source, File destination)

    1. public static void copyURLToFile(URL source, File destination) throws IOException {  
    2.   
    3.             InputStream input =source.openStream();  
    4.   
    5.             copyInputStreamToFile(input,destination);  
    6.   
    7.         }  



    根据一个Url拷贝字节到一个文件中,并且可以设置连接的超时时间和读取的超时时间

    copyURLToFile(URLsource, File destination, int connectionTimeout, int readTimeout)

    1. public static void copyURLToFile(URL source, File destination,int connectionTimeout, int readTimeout)throws IOException {  
    2.   
    3.             URLConnection connection =source.openConnection();  
    4.   
    5.            connection.setConnectTimeout(connectionTimeout);  
    6.   
    7.            connection.setReadTimeout(readTimeout);  
    8.   
    9.             InputStream input =connection.getInputStream();  
    10.   
    11.             copyInputStreamToFile(input,destination);  
    12.   
    13.         }  



    拷贝一个字节流到一个文件中,如果这个文件不存在则新创建一个,存在的话将被重写进内容copyInputStreamToFile(InputStream source, File destination)

       

    1. public static voidcopyInputStreamToFile(InputStream source, File destination) throws IOException{  
    2.   
    3.            try {  
    4.   
    5.                FileOutputStream output =openOutputStream(destination);  
    6.   
    7.                try {  
    8.   
    9.                    IOUtils.copy(source,output);  
    10.   
    11.                } finally {  
    12.   
    13.                   IOUtils.closeQuietly(output);  
    14.   
    15.                }  
    16.   
    17.            } finally {  
    18.   
    19.                IOUtils.closeQuietly(source);  
    20.   
    21.            }  
    22.   
    23.        }  



     

    递归的删除一个目录deleteDirectory(Filedirectory)

    1. public static void deleteDirectory(File directory) throws IOException {  
    2.   
    3.             if (!directory.exists()) {  
    4.   
    5.                 return;  
    6.   
    7.             }  
    8.   
    9.      
    10.   
    11.             if (!isSymlink(directory)) {  
    12.   
    13.                 cleanDirectory(directory);  
    14.   
    15.             }  
    16.   
    17.      
    18.   
    19.             if (!directory.delete()) {  
    20.   
    21.                 String message =  
    22.   
    23.                     "Unable to deletedirectory " + directory + ".";  
    24.   
    25.                 throw new IOException(message);  
    26.   
    27.             }  
    28.   
    29.         }  



    安静模式删除目录,操作过程中会抛出异常deleteQuietly(File file)

    1. public static boolean deleteQuietly(File file) {  
    2.   
    3.             if (file == null) {  
    4.   
    5.                 return false;  
    6.   
    7.             }  
    8.   
    9.             try {  
    10.   
    11.                 if (file.isDirectory()) {  
    12.   
    13.                     cleanDirectory(file);  
    14.   
    15.                 }  
    16.   
    17.             } catch (Exception ignored) {  
    18.   
    19.             }  
    20.   
    21.      
    22.   
    23.             try {  
    24.   
    25.                 return file.delete();  
    26.   
    27.             } catch (Exception ignored) {  
    28.   
    29.                 return false;  
    30.   
    31.             }  
    32.   
    33.         }  



     

     

    清除一个目录而不删除它cleanDirectory(Filedirectory)

    1. public static void cleanDirectory(File directory) throws IOException {  
    2.   
    3.             if (!directory.exists()) {  
    4.   
    5.                 String message = directory +" does not exist";  
    6.   
    7.                 throw new IllegalArgumentException(message);  
    8.   
    9.             }  
    10.   
    11.      
    12.   
    13.             if (!directory.isDirectory()) {  
    14.   
    15.                 String message = directory +" is not a directory";  
    16.   
    17.                 throw new IllegalArgumentException(message);  
    18.   
    19.             }  
    20.   
    21.      
    22.   
    23.             File[] files =directory.listFiles();  
    24.   
    25.             if (files == null) {  // null if security restricted  
    26.   
    27.                 throw new IOException("Failed to list contents of " + directory);  
    28.   
    29.             }  
    30.   
    31.      
    32.   
    33.             IOException exception = null;  
    34.   
    35.             for (File file : files) {  
    36.   
    37.                 try {  
    38.   
    39.                     forceDelete(file);  
    40.   
    41.                 } catch (IOException ioe) {  
    42.   
    43.                     exception = ioe;  
    44.   
    45.                 }  
    46.   
    47.             }  
    48.   
    49.      
    50.   
    51.             if (null != exception) {  
    52.   
    53.                 throw exception;  
    54.   
    55.             }  
    56.   
    57.         }  



    等待NFS来传播一个文件的创建,实施超时waitFor(File file, int seconds)

    1. public static boolean waitFor(File file, int seconds) {  
    2.   
    3.             int timeout = 0;  
    4.   
    5.             int tick = 0;  
    6.   
    7.             while (!file.exists()) {  
    8.   
    9.                 if (tick++ >= 10) {  
    10.   
    11.                     tick = 0;  
    12.   
    13.                     if (timeout++ > seconds){  
    14.   
    15.                         return false;  
    16.   
    17.                     }  
    18.   
    19.                 }  
    20.   
    21.                 try {  
    22.   
    23.                     Thread.sleep(100);  
    24.   
    25.                 } catch (InterruptedExceptionignore) {  
    26.   
    27.                     // ignore exception  
    28.   
    29.                 } catch (Exception ex) {  
    30.   
    31.                     break;  
    32.   
    33.                 }  
    34.   
    35.             }  
    36.   
    37.             return true;  
    38.   
    39.         }  



    把一个文件的内容读取到一个对应编码的字符串中去readFileToString(File file, String encoding)

      

    1. public static String readFileToString(Filefile, String encoding) throws IOException {  
    2.   
    3.             InputStream in = null;  
    4.   
    5.             try {  
    6.   
    7.                 in = openInputStream(file);  
    8.   
    9.                 return IOUtils.toString(in,encoding);  
    10.   
    11.             } finally {  
    12.   
    13.                 IOUtils.closeQuietly(in);  
    14.   
    15.             }  
    16.   
    17.         }  



     

    读取文件的内容到虚拟机的默认编码字符串readFileToString(File file)

    1. public static String readFileToString(Filefile) throws IOException {  
    2.   
    3.           return readFileToString(file,null);  
    4.   
    5.       }  



    把一个文件转换成字节数组返回readFileToByteArray(File file)

     

    1. public static byte[] readFileToByteArray(Filefile) throws IOException {  
    2.   
    3.            InputStream in = null;  
    4.   
    5.            try {  
    6.   
    7.                in = openInputStream(file);  
    8.   
    9.                return IOUtils.toByteArray(in);  
    10.   
    11.            } finally {  
    12.   
    13.                IOUtils.closeQuietly(in);  
    14.   
    15.            }  
    16.   
    17.        }  

     

     

    把文件中的内容逐行的拷贝到一个对应编码的list<String>中去

    1. public static List<String> readLines(File file, String encoding) throws IOException {  
    2.   
    3.             InputStream in = null;  
    4.   
    5.             try {  
    6.   
    7.                 in = openInputStream(file);  
    8.   
    9.                 return IOUtils.readLines(in,encoding);  
    10.   
    11.             } finally {  
    12.   
    13.                 IOUtils.closeQuietly(in);  
    14.   
    15.             }  
    16.   
    17.         }  



    把文件中的内容逐行的拷贝到一个虚拟机默认编码的list<String>中去

    1. public static List<String>readLines(File file) throws IOException {  
    2.   
    3.            return readLines(file, null);  
    4.   
    5.        }  



    根据对应编码返回对应文件内容的行迭代器lineIterator(File file, String encoding)

    1. public static LineIterator lineIterator(File file, String encoding) throws IOException{  
    2.   
    3.             InputStream in = null;  
    4.   
    5.             try {  
    6.   
    7.                 in = openInputStream(file);  
    8.   
    9.                 return IOUtils.lineIterator(in,encoding);  
    10.   
    11.             } catch (IOException ex) {  
    12.   
    13.                 IOUtils.closeQuietly(in);  
    14.   
    15.                throw ex;  
    16.   
    17.             } catch (RuntimeException ex) {  
    18.   
    19.                 IOUtils.closeQuietly(in);  
    20.   
    21.                 throw ex;  
    22.   
    23.             }  
    24.   
    25.         }  



    根据虚拟机默认编码返回对应文件内容的行迭代器lineIterator(File file)

    1. public static LineIterator lineIterator(Filefile) throws IOException {  
    2.   
    3.           return lineIterator(file, null);  
    4.   
    5.       }  



    根据对应编码把字符串写进对应的文件中writeStringToFile(File file, String data, String encoding)

    1. public static void writeStringToFile(File file, String data, String encoding) throws IOException {  
    2.   
    3.             OutputStream out = null;  
    4.   
    5.             try {  
    6.   
    7.                 out = openOutputStream(file);  
    8.   
    9.                 IOUtils.write(data, out,encoding);  
    10.   
    11.             } finally {  
    12.   
    13.                 IOUtils.closeQuietly(out);  
    14.   
    15.             }  
    16.   
    17.         }  

     

    根据虚拟机默认编码把字符串写进对应的文件中writeStringToFile(File file, String data)

    1. public static void writeStringToFile(Filefile, String data) throws IOException {  
    2.   
    3.           writeStringToFile(file, data,null);  
    4.   
    5.       }  



    根据虚拟机默认的编码把CharSequence写入到文件中(File file, CharSequence data)

    1. public static void write(File file, CharSequence data) throws IOException {  
    2.   
    3.             String str = data == null ? null :data.toString();  
    4.   
    5.             writeStringToFile(file, str);  
    6.   
    7.         }  



    根据对应的编码把CharSequence写入到文件中write(File file, CharSequence data, String encoding)

    1. public static void write(File file, CharSequence data, String encoding) throws IOException {  
    2.   
    3.             String str = data == null ? null :data.toString();  
    4.   
    5.             writeStringToFile(file, str,encoding);  
    6.   
    7.         }  



    把一个字节数组写入到指定的文件中writeByteArrayToFile(File file, byte[] data)

     

    1. public static void writeByteArrayToFile(Filefile, byte[] data) throws IOException {  
    2.   
    3.           OutputStream out = null;  
    4.   
    5.           try {  
    6.   
    7.               out = openOutputStream(file);  
    8.   
    9.               out.write(data);  
    10.   
    11.           } finally {  
    12.   
    13.               IOUtils.closeQuietly(out);  
    14.   
    15.           }  
    16.   
    17.       }  

     

     

    把集合中的内容根据对应编码逐项插入到文件中writeLines(File file, String encoding, Collection<?> lines)

     

    1. public static void writeLines(File file,String encoding, Collection<?> lines) throws IOException {  
    2.   
    3.             writeLines(file, encoding, lines,null);  
    4.   
    5.         }  



     

    把集合中的内容根据虚拟机默认编码逐项插入到文件中writeLines(File file, Collection<?> lines)

    1. public static void writeLines(File file, Collection<?> lines) throws IOException{  
    2.   
    3.             writeLines(file, null, lines,null);  
    4.   
    5.         }  



    把集合中的内容根据对应字符编码和行编码逐项插入到文件中

     

    1. public static void writeLines(File file,String encoding, Collection<?> lines, String lineEnding)  
    2.   
    3.           throws IOException {  
    4.   
    5.           OutputStream out = null;  
    6.   
    7.           try {  
    8.   
    9.               out = openOutputStream(file);  
    10.   
    11.               IOUtils.writeLines(lines,lineEnding, out, encoding);  
    12.   
    13.           } finally {  
    14.   
    15.               IOUtils.closeQuietly(out);  
    16.   
    17.           }  
    18.   
    19.       }  

     

     

    把集合中的内容根据对应行编码逐项插入到文件中

    1. public static void writeLines(File file, Collection<?> lines, String lineEnding)throws IOException {  
    2.   
    3.             writeLines(file, null, lines,lineEnding);  
    4.   
    5.         }  



    删除一个文件,如果是目录则递归删除forceDelete(File file)

     

    1. public static void forceDelete(File file)throws IOException {  
    2.   
    3.             if (file.isDirectory()) {  
    4.   
    5.                 deleteDirectory(file);  
    6.   
    7.             } else {  
    8.   
    9.                 boolean filePresent =file.exists();  
    10.   
    11.                 if (!file.delete()) {  
    12.   
    13.                     if (!filePresent){  
    14.   
    15.                         throw new FileNotFoundException("File does not exist: " + file);  
    16.   
    17.                     }  
    18.   
    19.                     String message =  
    20.   
    21.                         "Unable to deletefile: " + file;  
    22.   
    23.                     throw new IOException(message);  
    24.   
    25.                 }  
    26.   
    27.             }  
    28.   
    29.         }  



     

    当虚拟机退出关闭时删除文件forceDeleteOnExit(File file)

    1. public static void forceDeleteOnExit(File file) throws IOException {  
    2.   
    3.             if (file.isDirectory()) {  
    4.   
    5.                 deleteDirectoryOnExit(file);  
    6.   
    7.             } else {  
    8.   
    9.                 file.deleteOnExit();  
    10.   
    11.             }  
    12.   
    13.         }  



    当虚拟机退出关闭时递归删除一个目录deleteDirectoryOnExit(File directory)

    1. private static void deleteDirectoryOnExit(File directory) throws IOException {  
    2.   
    3.             if (!directory.exists()) {  
    4.   
    5.                 return;  
    6.   
    7.             }  
    8.   
    9.      
    10.   
    11.             if (!isSymlink(directory)) {  
    12.   
    13.                 cleanDirectoryOnExit(directory);  
    14.   
    15.             }  
    16.   
    17.             directory.deleteOnExit();  
    18.   
    19.         }  



    在虚拟机退出或者关闭时清除一个目录而不删除它

    1. private static void cleanDirectoryOnExit(Filedirectory) throws IOException {  
    2.   
    3.           if (!directory.exists()) {  
    4.   
    5.               String message = directory +" does not exist";  
    6.   
    7.               throw new IllegalArgumentException(message);  
    8.   
    9.           }  
    10.   
    11.    
    12.   
    13.           if (!directory.isDirectory()) {  
    14.   
    15.               String message = directory +" is not a directory";  
    16.   
    17.               throw new IllegalArgumentException(message);  
    18.   
    19.           }  
    20.   
    21.    
    22.   
    23.           File[] files =directory.listFiles();  
    24.   
    25.           if (files == null) {  // null if security restricted  
    26.   
    27.               throw new IOException("Failed to list contents of " + directory);  
    28.   
    29.           }  
    30.   
    31.    
    32.   
    33.           IOException exception = null;  
    34.   
    35.           for (File file : files) {  
    36.   
    37.               try {  
    38.   
    39.                   forceDeleteOnExit(file);  
    40.   
    41.               } catch (IOException ioe) {  
    42.   
    43.                   exception = ioe;  
    44.   
    45.               }  
    46.   
    47.           }  
    48.   
    49.    
    50.   
    51.           if (null != exception) {  
    52.   
    53.               throw exception;  
    54.   
    55.           }  
    56.   
    57.       }  



    创建一个目录除了不存在的父目录其他所必须的都可以创建forceMkdir(File directory)

    1. public static void forceMkdir(File directory) throws IOException {  
    2.   
    3.             if (directory.exists()) {  
    4.   
    5.                 if (!directory.isDirectory()) {  
    6.   
    7.                     String message =  
    8.   
    9.                         "File "  
    10.   
    11.                             + directory  
    12.   
    13.                             + " exists andis "  
    14.   
    15.                             + "not adirectory. Unable to create directory.";  
    16.   
    17.                     throw new IOException(message);  
    18.   
    19.                 }  
    20.   
    21.             } else {  
    22.   
    23.                 if (!directory.mkdirs()) {  
    24.   
    25.                     // Double-check that someother thread or process hasn't made  
    26.   
    27.                     // the directory in thebackground  
    28.   
    29.                     if (!directory.isDirectory())  
    30.   
    31.                     {  
    32.   
    33.                         String message =  
    34.   
    35.                             "Unable tocreate directory " + directory;  
    36.   
    37.                         throw new IOException(message);  
    38.   
    39.                     }  
    40.   
    41.                 }  
    42.   
    43.             }  
    44.   
    45.         }  



    获取文件或者目录的大小sizeOf(Filefile)

    1. public static long sizeOf(File file) {  
    2.   
    3.    
    4.   
    5.           if (!file.exists()) {  
    6.   
    7.               String message = file + "does not exist";  
    8.   
    9.               throw new IllegalArgumentException(message);  
    10.   
    11.           }  
    12.   
    13.    
    14.   
    15.           if (file.isDirectory()) {  
    16.   
    17.               return sizeOfDirectory(file);  
    18.   
    19.           } else {  
    20.   
    21.               return file.length();  
    22.   
    23.           }  
    24.   
    25.       }  



    获取目录的大小sizeOfDirectory(Filedirectory)

    1. public static long sizeOfDirectory(File directory) {  
    2.   
    3.             if (!directory.exists()) {  
    4.   
    5.                 String message = directory +" does not exist";  
    6.   
    7.                 throw new IllegalArgumentException(message);  
    8.   
    9.             }  
    10.   
    11.             if (!directory.isDirectory()) {  
    12.   
    13.                 String message = directory +" is not a directory";  
    14.   
    15.                 throw new IllegalArgumentException(message);  
    16.   
    17.             }  
    18.   
    19.      
    20.   
    21.             long size = 0;  
    22.   
    23.      
    24.   
    25.             File[] files =directory.listFiles();  
    26.   
    27.             if (files == null) {  // null if security restricted  
    28.   
    29.                 return 0L;  
    30.   
    31.             }  
    32.   
    33.             for (File file : files) {  
    34.   
    35.                 size += sizeOf(file);  
    36.   
    37.             }  
    38.   
    39.      
    40.   
    41.             return size;  
    42.   
    43.         }  



    测试指定文件的最后修改日期是否比reference的文件新isFileNewer(File file, Filereference)

    1. public static boolean isFileNewer(File file, File reference) {  
    2.   
    3.             if (reference == null) {  
    4.   
    5.                 throw new IllegalArgumentException("No specified reference file");  
    6.   
    7.             }  
    8.   
    9.             if (!reference.exists()) {  
    10.   
    11.                 throw new IllegalArgumentException("The reference file '"  
    12.   
    13.                         + reference + "'doesn't exist");  
    14.   
    15.             }  
    16.   
    17.             return isFileNewer(file,reference.lastModified());  
    18.   
    19.         }  



    检测指定文件的最后修改时间是否在指定日期之前isFileNewer(File file, Date date)

    1. public static boolean isFileNewer(File file, Date date) {  
    2.   
    3.             if (date == null) {  
    4.   
    5.                 throw new llegalArgumentException("No specified date");  
    6.   
    7.             }  
    8.   
    9.             return isFileNewer(file,date.getTime());  
    10.   
    11.         }  



    检测指定文件的最后修改时间(毫秒)是否在指定日期之前isFileNewer(File file, long timeMillis)

    1. public static boolean isFileNewer(File file, long timeMillis) {  
    2.   
    3.             if (file == null) {  
    4.   
    5.                 throw new IllegalArgumentException("No specified file");  
    6.   
    7.             }  
    8.   
    9.             if (!file.exists()) {  
    10.   
    11.                 return false;  
    12.   
    13.             }  
    14.   
    15.             return file.lastModified() >timeMillis;  
    16.   
    17.         }  



    检测指定文件的最后修改日期是否比reference文件的晚isFileOlder(File file, Filereference)

    1. public static boolean isFileOlder(File file, File reference) {  
    2.   
    3.             if (reference == null) {  
    4.   
    5.                 throw new IllegalArgumentException("No specified reference file");  
    6.   
    7.             }  
    8.   
    9.             if (!reference.exists()) {  
    10.   
    11.                 throw new IllegalArgumentException("The reference file '"  
    12.   
    13.                         + reference + "'doesn't exist");  
    14.   
    15.             }  
    16.   
    17.             return isFileOlder(file,reference.lastModified());  
    18.   
    19.         }  



    检测指定文件的最后修改时间是否在指定日期之后isFileOlder(File file, Date date)

    1. public static boolean isFileOlder(File file, Date date) {  
    2.   
    3.             if (date == null) {  
    4.   
    5.                 throw new IllegalArgumentException("No specified date");  
    6.   
    7.             }  
    8.   
    9.             return isFileOlder(file,date.getTime());  
    10.   
    11.         }  



    检测指定文件的最后修改时间(毫秒)是否在指定日期之后isFileOlder(File file, long timeMillis)

    1. public static boolean isFileOlder(Filefile, long timeMillis) {  
    2.   
    3.         if (file == null) {  
    4.   
    5.             throw new IllegalArgumentException("Nospecified file");  
    6.   
    7.         }  
    8.   
    9.         if (!file.exists()) {  
    10.   
    11.             return false;  
    12.   
    13.         }  
    14.   
    15.         return file.lastModified() <timeMillis;  
    16.   
    17.     }  



    计算使用CRC32校验程序文件的校验和checksumCRC32(File file)

    1. public static long checksumCRC32(File file) throws IOException {  
    2.   
    3.             CRC32 crc = new CRC32();  
    4.   
    5.             checksum(file, crc);  
    6.   
    7.             return crc.getValue();  
    8.   
    9.         }  



    计算一个文件使用指定的校验对象的校验checksum(Filefile, Checksum checksum)

    1. public static Checksum checksum(File file, Checksum checksum) throws IOException {  
    2.   
    3.             if (file.isDirectory()) {  
    4.   
    5.                 throw new IllegalArgumentException("Checksums can't be computed ondirectories");  
    6.   
    7.             }  
    8.   
    9.             InputStream in = null;  
    10.   
    11.             try {  
    12.   
    13.                 in = new CheckedInputStream(newFileInputStream(file), checksum);  
    14.   
    15.                 IOUtils.copy(in, newNullOutputStream());  
    16.   
    17.             } finally {  
    18.   
    19.                 IOUtils.closeQuietly(in);  
    20.   
    21.             }  
    22.   
    23.             return checksum;  
    24.   
    25.         }  



    移动目录到新的目录并且删除老的目录moveDirectory(File srcDir, File destDir)

    1. public static void moveDirectory(File srcDir, File destDir) throws IOException {  
    2.   
    3.             if (srcDir == null) {  
    4.   
    5.                 throw new NullPointerException("Source must not be null");  
    6.   
    7.             }  
    8.   
    9.             if (destDir == null) {  
    10.   
    11.                 throw new NullPointerException("Destination must not be null");  
    12.   
    13.             }  
    14.   
    15.             if (!srcDir.exists()) {  
    16.   
    17.                 throw new FileNotFoundException("Source '" + srcDir + "' does notexist");  
    18.   
    19.             }  
    20.   
    21.             if (!srcDir.isDirectory()) {  
    22.   
    23.                 throw new IOException("Source '" + srcDir + "' is not a directory");  
    24.   
    25.             }  
    26.   
    27.             if (destDir.exists()) {  
    28.   
    29.                 throw new FileExistsException("Destination '" + destDir + "' alreadyexists");  
    30.   
    31.             }  
    32.   
    33.             boolean rename = srcDir.renameTo(destDir);  
    34.   
    35.             if (!rename) {  
    36.   
    37.                 copyDirectory( srcDir, destDir);  
    38.   
    39.                 deleteDirectory( srcDir );  
    40.   
    41.                 if (srcDir.exists()) {  
    42.   
    43.                     throw new IOException("Failed to delete original directory '" + srcDir +  
    44.   
    45.                             "' after copyto '" + destDir + "'");  
    46.   
    47.                 }  
    48.   
    49.             }  
    50.   
    51.         }  



    把一个目录移动到另一个目录中去moveDirectoryToDirectory(File src, File destDir, booleancreateDestDir)

    1. public static void moveDirectoryToDirectory(File src, File destDir, booleancreateDestDir) throws IOException {  
    2.   
    3.             if (src == null) {  
    4.   
    5.                 throw new NullPointerException("Source must not be null");  
    6.   
    7.             }  
    8.   
    9.             if (destDir == null) {  
    10.   
    11.                 throw new NullPointerException("Destination directory must not be null");  
    12.   
    13.             }  
    14.   
    15.             if (!destDir.exists() &&createDestDir) {  
    16.   
    17.                 destDir.mkdirs();  
    18.   
    19.             }  
    20.   
    21.             if (!destDir.exists()) {  
    22.   
    23.                 throw new FileNotFoundException("Destination directory '" + destDir +  
    24.   
    25.                         "' does not exist[createDestDir=" + createDestDir +"]");  
    26.   
    27.             }  
    28.   
    29.             if (!destDir.isDirectory()) {  
    30.   
    31.                 throw new IOException("Destination'" + destDir + "' is not a directory");  
    32.   
    33.             }  
    34.   
    35.             moveDirectory(src, newFile(destDir, src.getName()));  
    36.   
    37.          
    38.   
    39.         }  



    复制文件到对应的文件中去moveFile(FilesrcFile, File destFile)

    1. public static void moveFile(File srcFile, File destFile) throws IOException {  
    2.   
    3.             if (srcFile == null) {  
    4.   
    5.                 throw new NullPointerException("Source must not be null");  
    6.   
    7.             }  
    8.   
    9.             if (destFile == null) {  
    10.   
    11.                 throw new NullPointerException("Destination must not be null");  
    12.   
    13.             }  
    14.   
    15.             if (!srcFile.exists()) {  
    16.   
    17.                 throw new FileNotFoundException("Source '" + srcFile + "' does notexist");  
    18.   
    19.             }  
    20.   
    21.             if (srcFile.isDirectory()) {  
    22.   
    23.                 throw new IOException("Source '" + srcFile + "' is a directory");  
    24.   
    25.             }  
    26.   
    27.             if (destFile.exists()) {  
    28.   
    29.                 throw new FileExistsException("Destination '" + destFile + "' alreadyexists");  
    30.   
    31.             }  
    32.   
    33.             if (destFile.isDirectory()) {  
    34.   
    35.                 throw new IOException("Destination '" + destFile + "' is adirectory");  
    36.   
    37.             }  
    38.   
    39.             boolean rename =srcFile.renameTo(destFile);  
    40.   
    41.             if (!rename) {  
    42.   
    43.                 copyFile( srcFile, destFile );  
    44.   
    45.                 if (!srcFile.delete()) {  
    46.   
    47.                    FileUtils.deleteQuietly(destFile);  
    48.   
    49.                     throw new IOException("Failed to delete original file '" + srcFile +  
    50.   
    51.                             "' after copyto '" + destFile + "'");  
    52.   
    53.                 }  
    54.   
    55.             }  
    56.   
    57.         }  



     

     

    复制文件到对应的文件中去,可设置当目标文件不存在时是否创建新的文件moveFile(File srcFile, File destFile)

     

    1. public static void moveFileToDirectory(File srcFile, File destDir, booleancreateDestDir) throws IOException {  
    2.   
    3.             if (srcFile == null) {  
    4.   
    5.                 throw new NullPointerException("Source must not be null");  
    6.   
    7.             }  
    8.   
    9.             if (destDir == null) {  
    10.   
    11.                 throw new NullPointerException("Destinationdirectory must not be null");  
    12.   
    13.             }  
    14.   
    15.             if (!destDir.exists() &&createDestDir) {  
    16.   
    17.                 destDir.mkdirs();  
    18.   
    19.             }  
    20.   
    21.             if (!destDir.exists()) {  
    22.   
    23.                 throw new FileNotFoundException("Destination directory '" + destDir +  
    24.   
    25.                         "' does not exist[createDestDir=" + createDestDir +"]");  
    26.   
    27.             }  
    28.   
    29.             if (!destDir.isDirectory()) {  
    30.   
    31.                 throw new IOException("Destination'" + destDir + "' is not a directory");  
    32.   
    33.             }  
    34.   
    35.             moveFile(srcFile, new File(destDir,srcFile.getName()));  
    36.   
    37.         }  



    移动文件或者目录到新的路径下,并且设置在目标路径不存在的情况下是否创建moveToDirectory(File src, File destDir, boolean createDestDir)

    1. public static void moveToDirectory(File src, File destDir, boolean createDestDir)throws IOException {  
    2.   
    3.            if (src == null) {  
    4.   
    5.                 throw new NullPointerException("Source must not be null");  
    6.   
    7.             }  
    8.   
    9.             if (destDir == null) {  
    10.   
    11.                 throw new NullPointerException("Destination must not be null");  
    12.   
    13.             }  
    14.   
    15.             if (!src.exists()) {  
    16.   
    17.                 throw new FileNotFoundException("Source '" + src + "' does notexist");  
    18.   
    19.             }  
    20.   
    21.             if (src.isDirectory()) {  
    22.   
    23.                 moveDirectoryToDirectory(src,destDir, createDestDir);  
    24.   
    25.             } else {  
    26.   
    27.                 moveFileToDirectory(src,destDir, createDestDir);  
    28.   
    29.             }  
    30.   
    31.         }  



    确定指定的文件是否是一个符号链接,而不是实际的文件。isSymlink(File file)

    1. public static boolean isSymlink(File file) throws IOException {  
    2.   
    3.             if (file == null) {  
    4.   
    5.                 throw new NullPointerException("File must not be null");  
    6.   
    7.             }  
    8.   
    9.             if(FilenameUtils.isSystemWindows()) {  
    10.   
    11.                 return false;  
    12.   
    13.             }  
    14.   
    15.             File fileInCanonicalDir = null;  
    16.   
    17.             if (file.getParent() == null) {  
    18.   
    19.                 fileInCanonicalDir = file;  
    20.   
    21.             } else {  
    22.   
    23.                 File canonicalDir =file.getParentFile().getCanonicalFile();  
    24.   
    25.                 fileInCanonicalDir = newFile(canonicalDir, file.getName());  
    26.   
    27.             }  
    28.   
    29.              
    30.   
    31.             if(fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())){  
    32.   
    33.                 return false;  
    34.   
    35.             } else {  
    36.   
    37.                 return true;  
    38.   
    39.             }  
    40.   
    41.         }  
  • 相关阅读:
    extjs grid renderer用法
    spket对Extjs4的支持方法 eclipse插件spket安装 extjs4 提示
    Delphi关于多线程同步的一些方法 zb
    指针学习(一) zb
    struts2中action实现ModelDriven后无法返回json的问题
    前端css编写规范
    javascript 原型链
    chrome bug
    浏览器缓存
    RegExp
  • 原文地址:https://www.cnblogs.com/webmen/p/5739098.html
Copyright © 2011-2022 走看看