對文件操作之FileUtils方法大全

獲取系統的臨時目錄路徑:getTempDirectoryPath()

public static String getTempDirectoryPath() {  

           return System.getProperty("java.io.tmpdir");  

 }  

獲取代表系統臨時目錄的文件:getTempDirectory ()

public static File getTempDirectory() {  

           return new File(getTempDirectoryPath());  

 }  

獲取用戶的主目錄路徑:getUserDirectoryPath()

public static String getUserDirectoryPath() {  

           return System.getProperty("user.home");  

 }  

獲取代表用戶主目錄的文件:getUserDirectory()

public static File getUserDirectory() {  

           return new File(getUserDirectoryPath());  

}  

根據指定的文件獲取一個新的文件輸入流:openInputStream(File file)

public static FileInputStream openInputStream(File file) throws IOException {  

           if (file.exists()) {  

               if (file.isDirectory()) {  

                   throw new IOException("File '" + file + "' exists but is adirectory");  

               }  

               if (file.canRead() == false) {  

                   throw new IOException("File '" + file + "' cannot be read");  

               }  

           } else {  

               throw newFileNotFoundException("File '" + file + "' does notexist");  

           }  

           return new FileInputStream(file);  

       }  

根據指定的文件獲取一個新的文件輸出流:openOutputStream (File file)

public static FileOutputStream openOutputStream(File file) throws IOException {  

           if (file.exists()) {  

               if (file.isDirectory()) {  

                   throw new IOException("File'" + file + "' exists but is a directory");  

               }  

               if (file.canWrite() == false) {  

                   throw new IOException("File '" + file + "' cannot be written to");  

               }  

           } else {  

               File parent = file.getParentFile();  

               if (parent != null &&parent.exists() == false) {  

                   if (parent.mkdirs() ==false) {  

                       throw new IOException("File '" + file + "' could not be created");  

                   }  

               }  

           }  

           return new FileOutputStream(file);  

       }  

字節轉換成直觀帶單位的值(包括單位GB,MB,KB或字節)byteCountToDisplaySize(long size)

public static StringbyteCountToDisplaySize(long size) {  

          String displaySize;  

          if (size / ONE_GB > 0) {  

              displaySize =String.valueOf(size / ONE_GB) + " GB";  

          } else if (size / ONE_MB > 0) {  

              displaySize =String.valueOf(size / ONE_MB) + " MB";  

          } else if (size / ONE_KB > 0) {  

              displaySize =String.valueOf(size / ONE_KB) + " KB";  

          } else {  

              displaySize =String.valueOf(size) + " bytes";  

          }  

          return displaySize;  

      } 

創建一個空文件,若文件應經存在則只更改文件的最近修改時間:touch(File file)

public static void touch(File file) throws IOException {  

         if (!file.exists()) {  

             OutputStream out =openOutputStream(file);  

             IOUtils.closeQuietly(out);  

         }  

         boolean success =file.setLastModified(System.currentTimeMillis());  

         if (!success) {  

             throw new IOException("Unableto set the last modification time for " + file);  

         }  

     }

把相應的文件集合轉換成文件數組convertFileCollectionToFileArray(Collection files)

public static File[] convertFileCollectionToFileArray(Collection<File> files) {  

            return files.toArray(newFile[files.size()]);  

       } 

根據一個過濾規則獲取一個目錄下的文件innerListFiles(Collection files, File directory,IOFileFilterfilter)

private static void innerListFiles(Collection<File> files, File directory,  

               IOFileFilter filter) {  

           File[] found =directory.listFiles((FileFilter) filter);  

           if (found != null) {  

               for (File file : found) {  

                   if (file.isDirectory()) {  

                       innerListFiles(files,file, filter);  

                   } else {  

                       files.add(file);  

                   }  

               }  

           }  

       } 

根據一個IOFileFilter過濾規則獲取一個目錄下的文件集合listFiles( File directory, IOFileFilterfileFilter, IOFileFilter dirFilter)

public static Collection<File> listFiles(  

               File directory, IOFileFilterfileFilter, IOFileFilter dirFilter) {  

           if (!directory.isDirectory()) {  

               throw newIllegalArgumentException(  

                       "Parameter'directory' is not a directory");  

           }  

           if (fileFilter == null) {  

               throw newNullPointerException("Parameter 'fileFilter' is null");  

           }  



           //Setup effective file filter  

           IOFileFilter effFileFilter =FileFilterUtils.and(fileFilter,  

               FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));  



           //Setup effective directory filter  

           IOFileFilter effDirFilter;  

           if (dirFilter == null) {  

               effDirFilter =FalseFileFilter.INSTANCE;  

           } else {  

               effDirFilter =FileFilterUtils.and(dirFilter,  

                  DirectoryFileFilter.INSTANCE);  

           }  



           //Find files  

           Collection<File> files = newjava.util.LinkedList<File>();  

           innerListFiles(files, directory,  

              FileFilterUtils.or(effFileFilter, effDirFilter));  

           return files;  

       }  

根據一個IOFileFilter過濾規則獲取一個目錄下的文件集合的Iterator迭代器iterateFiles( File directory, IOFileFilterfileFilter, IOFileFilter dirFilter)

public static Iterator<File> iterateFiles( File directory, IOFileFilterfileFilter, IOFileFilter dirFilter) {  

      return listFiles(directory,fileFilter, dirFilter).iterator();  

  }  

把指定的字符串數組變成後綴名格式字符串數組toSuffixes(String[] extensions)

private static String[] toSuffixes(String[] extensions) {  

           String[] suffixes = new String[extensions.length];  

           for (int i = 0; i <extensions.length; i++) {  

               suffixes[i] = "." +extensions[i];  

           }  

           return suffixes;  

       }  

查找一個目錄下面符合對應擴展名的文件的集合listFiles(File directory, String[]extensions, boolean recursive)

public static Collection<File> listFiles( File directory, String[]extensions, boolean recursive) {  

           IOFileFilter filter;  

           if (extensions == null) {  

               filter =TrueFileFilter.INSTANCE;  

           } else {  

               String[] suffixes =toSuffixes(extensions);  

               filter = new SuffixFileFilter(suffixes);  

           }  

           return listFiles(directory, filter,  

               (recursive ?TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE));  

       }  

查找一個目錄下面符合對應擴展名的文件的集合的迭代器Iterator iterateFiles( File directory, String[]extensions, boolean recursive)

public static Iterator<File> iterateFiles( File directory, String[]extensions, boolean recursive) {  

           return listFiles(directory,extensions, recursive).iterator();  

       }  

判斷兩個文件是否相等contentEquals(Filefile1, File file2)

public static boolean contentEquals(File file1, File file2) throws IOException {  

           boolean file1Exists =file1.exists();  

           if (file1Exists != file2.exists()) {  

               return false;  

           }  
           if (!file1Exists) {  

               // two not existing files are equal  

               return true;  

           }   
           if (file1.isDirectory() ||file2.isDirectory()) {  

               // don't want to compare directory contents  

               throw new IOException("Can't compare directories, only files");  

           }    
           if (file1.length() !=file2.length()) {  

               // lengths differ, cannot be equal  

               return false;  

           }           if(file1.getCanonicalFile().equals(file2.getCanonicalFile())) {  

               // same file  

               return true;  

           }  
           InputStream input1 = null;  

           InputStream input2 = null;  

           try {  

               input1 = newFileInputStream(file1);  

               input2 = newFileInputStream(file2);  

               returnIOUtils.contentEquals(input1, input2);  

           } finally {  

               IOUtils.closeQuietly(input1);  

               IOUtils.closeQuietly(input2);  

           }  

       } 

根據一個Url來創建一個文件toFile(URL url)

public static File toFile(URL url) {  

           if (url == null ||!"file".equalsIgnoreCase(url.getProtocol())) {  

               return null;  

           } else {  

               String filename =url.getFile().replace('/', File.separatorChar);  

               filename = decodeUrl(filename);  

               return new File(filename);  

           }  

       }  

對一個Url字符串進行將指定的URL按照RFC 3986進行轉換decodeUrl(Stringurl)

static String decodeUrl(String url) {  

           String decoded = url;  

           if (url != null &&url.indexOf('%') >= 0) {  

               int n = url.length();  

               StringBuffer buffer = newStringBuffer();  

               ByteBuffer bytes =ByteBuffer.allocate(n);  

               for (int i = 0; i < n;) {  

                   if (url.charAt(i) == '%') {  

                       try {  

                           do {  

                               byte octet =(byte) Integer.parseInt(url.substring(i + 1, i + 3), 16);  

                              bytes.put(octet);  

                               i += 3;  

                           } while (i < n&& url.charAt(i) == '%');  

                           continue;  

                       } catch(RuntimeException e) {  

                           // malformedpercent-encoded octet, fall through and  

                           // append charactersliterally  

                       } finally {  

                           if (bytes.position()> 0) {  

                               bytes.flip();  

                              buffer.append(UTF8.decode(bytes).toString());  

                               bytes.clear();  

                           }  

                       }  

                   }  

                  buffer.append(url.charAt(i++));  

               }  

               decoded = buffer.toString();  

           }  

           return decoded;  

       }  

將一個URL數組轉化成一個文件數組toFiles(URL[] urls)

public static File[]  toFiles(URL[] urls) {  

           if (urls == null || urls.length ==0) {  

               return EMPTY_FILE_ARRAY;  

           }  

           File[] files = newFile[urls.length];  

           for (int i = 0; i < urls.length;i++) {  

               URL url = urls[i];  

               if (url != null) {  

                   if(url.getProtocol().equals("file") == false) {  

                       throw newIllegalArgumentException(  

                               "URL couldnot be converted to a File: " + url);  

                   }  

                   files[i] = toFile(url);  

               }  

           }  

           return files;  

       }  

將一個文件數組轉化成一個URL數組toURLs(File[] files)

public static URL[]   toURLs(File[] files)throws IOException {  

          URL[] urls = new URL[files.length];  



          for (int i = 0; i < urls.length;i++) {  

              urls[i] =files[i].toURI().toURL();  

          }  



          return urls;  

      }  

拷貝一個文件到指定的目錄文件copyFileToDirectory(File srcFile, File destDir)

public static void copyFileToDirectory(File srcFile, File destDir) throws IOException{  

           copyFileToDirectory(srcFile,destDir, true);  

       }  

拷貝一個文件到指定的目錄文件並且設置是否更新文件的最近修改時間copyFileToDirectory(File srcFile, File destDir, booleanpreserveFileDate)

public static void copyFileToDirectory(File srcFile, File destDir, booleanpreserveFileDate) throws IOException {  

           if (destDir == null) {  

               throw new NullPointerException("Destination must not be null");  

           }  

           if (destDir.exists() &&destDir.isDirectory() == false) {  

               throw new IllegalArgumentException("Destination '" + destDir + "' is not adirectory");  

           }  

           File destFile = new File(destDir,srcFile.getName());  

           copyFile(srcFile, destFile,preserveFileDate);  

       }  

拷貝文件到新的文件中並且保存最近修改時間copyFile(File srcFile, File destFile)

public static void copyFile(File srcFile, File destFile) throws IOException {  

           copyFile(srcFile, destFile, true);  

       }  

拷貝文件到新的文件中並且設置是否保存最近修改時間copyFile(File srcFile, File destFile,boolean preserveFileDate)

public static void copyFile(File srcFile, File destFile,boolean preserveFileDate) throwsIOException {  

           if (srcFile == null) {  

               throw new NullPointerException("Source must not be null");  

           }  

           if (destFile == null) {  

               throw new NullPointerException("Destination must not be null");  

           }  

           if (srcFile.exists() == false) {  

               throw new FileNotFoundException("Source '" + srcFile + "' does not exist");  

           }  

           if (srcFile.isDirectory()) {  

               throw new IOException("Source '" + srcFile + "' exists but is a directory");  

           }  

           if(srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {  

               throw new IOException("Source '" + srcFile + "' and destination '" +destFile + "' are the same");  

           }  

           if (destFile.getParentFile() != null&& destFile.getParentFile().exists() == false) {  

               if(destFile.getParentFile().mkdirs() == false) {  

                   throw new IOException("Destination '" + destFile + "' directory cannot becreated");  

               }  

           }  

           if (destFile.exists() &&destFile.canWrite() == false) {  

               throw new IOException("Destination '" + destFile + "' exists but is read-only");  

           }  

           doCopyFile(srcFile, destFile,preserveFileDate);  

       }  

拷貝文件到新的文件中並且設置是否保存最近修改時間doCopyFile(File srcFile, File destFile, boolean preserveFileDate)

private static void doCopyFile(File srcFile,File destFile, boolean preserveFileDate) throws IOException {  

          if (destFile.exists() &&destFile.isDirectory()) {  

              throw new IOException("Destination '" + destFile + "' exists but is a directory");  

          }  



          FileInputStream fis = null;  

          FileOutputStream fos = null;  

          FileChannel input = null;  

          FileChannel output = null;  

          try {  

              fis = newFileInputStream(srcFile);  

              fos = newFileOutputStream(destFile);  

              input  = fis.getChannel();  

              output = fos.getChannel();  

              long size = input.size();  

              long pos = 0;  

              long count = 0;  

              while (pos < size) {  

                  count = (size - pos) >FIFTY_MB ? FIFTY_MB : (size - pos);  

                  pos +=output.transferFrom(input, pos, count);  

              }  

          } finally {  

              IOUtils.closeQuietly(output);  

              IOUtils.closeQuietly(fos);  

              IOUtils.closeQuietly(input);  

              IOUtils.closeQuietly(fis);  

          }  



          if (srcFile.length() !=destFile.length()) {  

              throw new IOException("Failed to copy full contents from '" +  

                      srcFile + "' to '"+ destFile + "'");  

          }  

          if (preserveFileDate) {  

             destFile.setLastModified(srcFile.lastModified());  

          }  

      }  

將一個目錄拷貝到另一目錄中,並且保存最近更新時間copyDirectoryToDirectory(File srcDir, File destDir)

public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException {  

           if (srcDir == null) {  

               throw new NullPointerException("Source must not be null");  

           }  

           if (srcDir.exists() &&srcDir.isDirectory() == false) {  

               throw new IllegalArgumentException("Source'" + destDir + "' is not a directory");  

           }  

           if (destDir == null) {  

               throw new NullPointerException("Destination must not be null");  

           }  

           if (destDir.exists() &&destDir.isDirectory() == false) {  

               throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");  

           }  

           copyDirectory(srcDir, newFile(destDir, srcDir.getName()), true);  

       }  

拷貝整個目錄到新的位置,並且保存最近修改時間copyDirectory(File srcDir, File destDir)

public static void copyDirectory(File srcDir, File destDir) throws IOException{  

         copyDirectory(srcDir, destDir,true);  

     }  

拷貝整個目錄到新的位置,並且設置是否保存最近修改時間copyDirectory(File srcDir, File destDir, boolean preserveFileDate)

public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException {  

           copyDirectory(srcDir, destDir, null,preserveFileDate);  

       }  

拷貝過濾後的目錄到指定的位置,並且保存最近修改時間copyDirectory(File srcDir, File destDir, FileFilter filter)

public static void copyDirectory(File srcDir, File destDir, FileFilter filter) throws IOException {  

           copyDirectory(srcDir, destDir,filter, true);  

       }  

拷貝過濾後的目錄到指定的位置,並且設置是否保存最近修改時間copyDirectory(File srcDir, File destDir,FileFilter filter, booleanpreserveFileDate)

public static void copyDirectory(File srcDir, File destDir,FileFilter filter, booleanpreserveFileDate) throws IOException {  

            if (srcDir == null) {  

                throw new NullPointerException("Source must not be null");  

            }  

            if (destDir == null) {  

                throw new NullPointerException("Destination must not be null");  

            }  

            if (srcDir.exists() == false) {  

                throw new FileNotFoundException("Source '" + srcDir + "' does not exist");  

            }  

            if (srcDir.isDirectory() == false){  

                throw new IOException("Source '" + srcDir + "' exists but is not a directory");  

            }  

            if(srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {  

                throw new IOException("Source '" + srcDir + "' and destination '" +destDir + "' are the same");  

            }  



            // Cater for destination being directorywithin the source directory (see IO-141)  

            List<String> exclusionList =null;  

            if(destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {  

                File[] srcFiles = filter ==null ? srcDir.listFiles() : srcDir.listFiles(filter);  

                if (srcFiles != null &&srcFiles.length > 0) {  

                    exclusionList = newArrayList<String>(srcFiles.length);  

                    for (File srcFile :srcFiles) {  

                        File copiedFile = new File(destDir, srcFile.getName());  

                       exclusionList.add(copiedFile.getCanonicalPath());  

                    }  

                }  

            }  

            doCopyDirectory(srcDir, destDir,filter, preserveFileDate, exclusionList);  

        }  

內部拷貝目錄的方法doCopyDirectory(FilesrcDir, File destDir, FileFilter filter, boolean preserveFileDate,List exclusionList)

private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter,boolean preserveFileDate,List<String> exclusionList) throws IOException {  

            // recurse  

            File[] files = filter == null ?srcDir.listFiles() : srcDir.listFiles(filter);  

            if (files == null) {  // null if security restricted  

                throw new IOException("Failed to list contents of " + srcDir);  

            }  

            if (destDir.exists()) {  

                if (destDir.isDirectory() ==false) {  

                    throw new IOException("Destination '" + destDir + "' exists but is not a directory");  

                }  

            } else {  

                if (destDir.mkdirs() == false){  

                    throw new IOException("Destination '" + destDir + "' directory cannot be created");  

                }  

            }  

            if (destDir.canWrite() == false) {  

                throw new IOException("Destination '" + destDir + "' cannot be written to");  

            }  

            for (File file : files) {  

                File copiedFile = newFile(destDir, file.getName());  

                if (exclusionList == null ||!exclusionList.contains(file.getCanonicalPath())) {  

                    if (file.isDirectory()) {  

                        doCopyDirectory(file,copiedFile, filter, preserveFileDate, exclusionList);  

                    } else {  

                        doCopyFile(file,copiedFile, preserveFileDate);  

                    }  

                }  

            }  



            // Do this last, as the above hasprobably affected directory metadata  

            if (preserveFileDate) {  

               destDir.setLastModified(srcDir.lastModified());  

            }  

        }  

根據一個Url拷貝字節到一個文件中copyURLToFile(URL source, File destination)

public static void copyURLToFile(URL source, File destination) throws IOException {  

            InputStream input =source.openStream();  

            copyInputStreamToFile(input,destination);  

        }  

根據一個Url拷貝字節到一個文件中,並且可以設置連接的超時時間和讀取的超時時間
copyURLToFile(URLsource, File destination, int connectionTimeout, int readTimeout)

public static void copyURLToFile(URL source, File destination,int connectionTimeout, int readTimeout)throws IOException {  

            URLConnection connection =source.openConnection();  

           connection.setConnectTimeout(connectionTimeout);  

           connection.setReadTimeout(readTimeout);  

            InputStream input =connection.getInputStream();  

            copyInputStreamToFile(input,destination);  

        }  

拷貝一個字節流到一個文件中,如果這個文件不存在則新創建一個,存在的話將被重寫進內容copyInputStreamToFile(InputStream source, File destination)

public static voidcopyInputStreamToFile(InputStream source, File destination) throws IOException{  

           try {  

               FileOutputStream output =openOutputStream(destination);  

               try {  

                   IOUtils.copy(source,output);  

               } finally {  

                  IOUtils.closeQuietly(output);  

               }  

           } finally {  

               IOUtils.closeQuietly(source);  

           }  

       }  

遞歸的刪除一個目錄deleteDirectory(Filedirectory)

public static void deleteDirectory(File directory) throws IOException {  

            if (!directory.exists()) {  

                return;  

            }  



            if (!isSymlink(directory)) {  

                cleanDirectory(directory);  

            }  



            if (!directory.delete()) {  

                String message =  

                    "Unable to deletedirectory " + directory + ".";  

                throw new IOException(message);  

            }  

        }  

安靜模式刪除目錄,操作過程中會拋出異常deleteQuietly(File file)

public static boolean deleteQuietly(File file) {  

            if (file == null) {  

                return false;  

            }  

            try {  

                if (file.isDirectory()) {  

                    cleanDirectory(file);  

                }  

            } catch (Exception ignored) {  

            }  



            try {  

                return file.delete();  

            } catch (Exception ignored) {  

                return false;  

            }  

        }  



清除一個目錄而不刪除它cleanDirectory(Filedirectory)

public static void cleanDirectory(File directory) throws IOException {  

            if (!directory.exists()) {  

                String message = directory +" does not exist";  

                throw new IllegalArgumentException(message);  

            }  



            if (!directory.isDirectory()) {  

                String message = directory +" is not a directory";  

                throw new IllegalArgumentException(message);  

            }  



            File[] files =directory.listFiles();  

            if (files == null) {  // null if security restricted  

                throw new IOException("Failed to list contents of " + directory);  

            }  



            IOException exception = null;  

            for (File file : files) {  

                try {  

                    forceDelete(file);  

                } catch (IOException ioe) {  

                    exception = ioe;  

                }  

            }  



            if (null != exception) {  

                throw exception;  

            }  

        }  

等待NFS來傳播一個文件的創建,實施超時waitFor(File file, int seconds)

public static boolean waitFor(File file, int seconds) {  

            int timeout = 0;  

            int tick = 0;  

            while (!file.exists()) {  

                if (tick++ >= 10) {  

                    tick = 0;  

                    if (timeout++ > seconds){  

                        return false;  

                    }  

                }  

                try {  

                    Thread.sleep(100);  

                } catch (InterruptedExceptionignore) {  

                    // ignore exception  

                } catch (Exception ex) {  

                    break;  

                }  

            }  

            return true;  

        }  

把一個文件的內容讀取到一個對應編碼的字符串中去readFileToString(File file, String encoding)

public static String readFileToString(Filefile, String encoding) throws IOException {  

            InputStream in = null;  

            try {  

                in = openInputStream(file);  

                return IOUtils.toString(in,encoding);  

            } finally {  

                IOUtils.closeQuietly(in);  

            }  

        }  

讀取文件的內容到虛擬機的默認編碼字符串readFileToString(File file)

public static String readFileToString(Filefile) throws IOException {  

          return readFileToString(file,null);  

      }  

把一個文件轉換成字節數組返回readFileToByteArray(File file)

public static byte[] readFileToByteArray(Filefile) throws IOException {  

           InputStream in = null;  

           try {  

               in = openInputStream(file);  

               return IOUtils.toByteArray(in);  

           } finally {  

               IOUtils.closeQuietly(in);  

           }  

       }  

把文件中的內容逐行的拷貝到一個對應編碼的list中去

public static List<String> readLines(File file, String encoding) throws IOException {  

            InputStream in = null;  

            try {  

                in = openInputStream(file);  

                return IOUtils.readLines(in,encoding);  

            } finally {  

                IOUtils.closeQuietly(in);  

            }  

        }  

把文件中的內容逐行的拷貝到一個虛擬機默認編碼的list中去

public static List<String>readLines(File file) throws IOException {  

           return readLines(file, null);  

       }  

根據對應編碼返回對應文件內容的行迭代器lineIterator(File file, String encoding)

public static LineIterator lineIterator(File file, String encoding) throws IOException{  

            InputStream in = null;  

            try {  

                in = openInputStream(file);  

                return IOUtils.lineIterator(in,encoding);  

            } catch (IOException ex) {  

                IOUtils.closeQuietly(in);  

               throw ex;  

            } catch (RuntimeException ex) {  

                IOUtils.closeQuietly(in);  

                throw ex;  

            }  

        }  

根據虛擬機默認編碼返回對應文件內容的行迭代器lineIterator(File file)

public static LineIterator lineIterator(Filefile) throws IOException {  

          return lineIterator(file, null);  

      }  

根據對應編碼把字符串寫進對應的文件中writeStringToFile(File file, String data, String encoding)

public static void writeStringToFile(File file, String data, String encoding) throws IOException {  

            OutputStream out = null;  

            try {  

                out = openOutputStream(file);  

                IOUtils.write(data, out,encoding);  

            } finally {  

                IOUtils.closeQuietly(out);  

            }  

        }  

根據虛擬機默認編碼把字符串寫進對應的文件中writeStringToFile(File file, String data)

public static void writeStringToFile(Filefile, String data) throws IOException {  

          writeStringToFile(file, data,null);  

      }  

根據虛擬機默認的編碼把CharSequence寫入到文件中(File file, CharSequence data)

public static void write(File file, CharSequence data) throws IOException {  

            String str = data == null ? null :data.toString();  

            writeStringToFile(file, str);  

        }  

根據對應的編碼把CharSequence寫入到文件中write(File file, CharSequence data, String encoding)

public static void write(File file, CharSequence data, String encoding) throws IOException {  

            String str = data == null ? null :data.toString();  

            writeStringToFile(file, str,encoding);  

        }  

把一個字節數組寫入到指定的文件中writeByteArrayToFile(File file, byte[] data)

public static void writeByteArrayToFile(Filefile, byte[] data) throws IOException {  

          OutputStream out = null;  

          try {  

              out = openOutputStream(file);  

              out.write(data);  

          } finally {  

              IOUtils.closeQuietly(out);  

          }  

      }  

把集合中的內容根據對應編碼逐項插入到文件中writeLines(File file, String encoding, Collection

public static void writeLines(File file,String encoding, Collection<?> lines) throws IOException {  

            writeLines(file, encoding, lines,null);  

        }  

把集合中的內容根據虛擬機默認編碼逐項插入到文件中writeLines(File file, Collection

public static void writeLines(File file, Collection<?> lines) throws IOException{  

            writeLines(file, null, lines,null);  

        }  

把集合中的內容根據對應字符編碼和行編碼逐項插入到文件中

public static void writeLines(File file,String encoding, Collection<?> lines, String lineEnding)  

          throws IOException {  

          OutputStream out = null;  

          try {  

              out = openOutputStream(file);  

              IOUtils.writeLines(lines,lineEnding, out, encoding);  

          } finally {  

              IOUtils.closeQuietly(out);  

          }  

      }  

把集合中的內容根據對應行編碼逐項插入到文件中

public static void writeLines(File file, Collection<?> lines, String lineEnding)throws IOException {  

            writeLines(file, null, lines,lineEnding);  

        }  

刪除一個文件,如果是目錄則遞歸刪除forceDelete(File file)

public static void forceDelete(File file)throws IOException {  

            if (file.isDirectory()) {  

                deleteDirectory(file);  

            } else {  

                boolean filePresent =file.exists();  

                if (!file.delete()) {  

                    if (!filePresent){  

                        throw new FileNotFoundException("File does not exist: " + file);  

                    }  

                    String message =  

                        "Unable to deletefile: " + file;  

                    throw new IOException(message);  

                }  

            }  

        }  

當虛擬機退出關閉時刪除文件forceDeleteOnExit(File file)

public static void forceDeleteOnExit(File file) throws IOException {  

            if (file.isDirectory()) {  

                deleteDirectoryOnExit(file);  

            } else {  

                file.deleteOnExit();  

            }  

        }  

當虛擬機退出關閉時遞歸刪除一個目錄deleteDirectoryOnExit(File directory)

private static void deleteDirectoryOnExit(File directory) throws IOException {  

            if (!directory.exists()) {  

                return;  

            }  



            if (!isSymlink(directory)) {  

                cleanDirectoryOnExit(directory);  

            }  

            directory.deleteOnExit();  

        }  

在虛擬機退出或者關閉時清除一個目錄而不刪除它

private static void cleanDirectoryOnExit(Filedirectory) throws IOException {  

          if (!directory.exists()) {  

              String message = directory +" does not exist";  

              throw new IllegalArgumentException(message);  

          }  



          if (!directory.isDirectory()) {  

              String message = directory +" is not a directory";  

              throw new IllegalArgumentException(message);  

          }  



          File[] files =directory.listFiles();  

          if (files == null) {  // null if security restricted  

              throw new IOException("Failed to list contents of " + directory);  

          }  



          IOException exception = null;  

          for (File file : files) {  

              try {  

                  forceDeleteOnExit(file);  

              } catch (IOException ioe) {  

                  exception = ioe;  

              }  

          }  



          if (null != exception) {  

              throw exception;  

          }  

      }  

創建一個目錄除了不存在的父目錄其他所必須的都可以創建forceMkdir(File directory)

public static void forceMkdir(File directory) throws IOException {  

            if (directory.exists()) {  

                if (!directory.isDirectory()) {  

                    String message =  

                        "File "  

                            + directory  

                            + " exists andis "  

                            + "not a directory. Unable to create directory.";  

                    throw new IOException(message);  

                }  

            } else {  

                if (!directory.mkdirs()) {  

                    // Double-check that someother thread or process hasn't made  

                    // the directory in thebackground  

                    if (!directory.isDirectory())  

                    {  

                        String message =  

                            "Unable tocreate directory " + directory;  

                        throw new IOException(message);  

                    }  

                }  

            }  

        }  

獲取文件或者目錄的大小sizeOf(Filefile)

public static long sizeOf(File file) {  



          if (!file.exists()) {  

              String message = file + "does not exist";  

              throw new IllegalArgumentException(message);  

          }  



          if (file.isDirectory()) {  

              return sizeOfDirectory(file);  

          } else {  

              return file.length();  

          }  

      }  

獲取目錄的大小sizeOfDirectory(Filedirectory)

public static long sizeOfDirectory(File directory) {  

            if (!directory.exists()) {  

                String message = directory +" does not exist";  

                throw new IllegalArgumentException(message);  

            }  

            if (!directory.isDirectory()) {  

                String message = directory +" is not a directory";  

                throw new IllegalArgumentException(message);  

            }  



            long size = 0;  



            File[] files =directory.listFiles();  

            if (files == null) {  // null if security restricted  

                return 0L;  

            }  

            for (File file : files) {  

                size += sizeOf(file);  

            }  



            return size;  

        }  

測試指定文件的最後修改日期是否比reference的文件新isFileNewer(File file, Filereference)

public static boolean isFileNewer(File file, File reference) {  

            if (reference == null) {  

                throw new IllegalArgumentException("No specified reference file");  

            }  

            if (!reference.exists()) {  

                throw new IllegalArgumentException("The reference file '"  

                        + reference + "'doesn't exist");  

            }  

            return isFileNewer(file,reference.lastModified());  

        }  

檢測指定文件的最後修改時間是否在指定日期之前isFileNewer(File file, Date date)

public static boolean isFileNewer(File file, Date date) {  

            if (date == null) {  

                throw new llegalArgumentException("No specified date");  

            }  

            return isFileNewer(file,date.getTime());  

        }  

檢測指定文件的最後修改時間(毫秒)是否在指定日期之前isFileNewer(File file, long timeMillis)

public static boolean isFileNewer(File file, long timeMillis) {  

            if (file == null) {  

                throw new IllegalArgumentException("No specified file");  

            }  

            if (!file.exists()) {  

                return false;  

            }  

            return file.lastModified() >timeMillis;  

        }  

檢測指定文件的最後修改日期是否比reference文件的晚isFileOlder(File file, Filereference)

public static boolean isFileOlder(File file, File reference) {  

            if (reference == null) {  

                throw new IllegalArgumentException("No specified reference file");  

            }  

            if (!reference.exists()) {  

                throw new IllegalArgumentException("The reference file '"  

                        + reference + "'doesn't exist");  

            }  

            return isFileOlder(file,reference.lastModified());  

        }  

檢測指定文件的最後修改時間是否在指定日期之後isFileOlder(File file, Date date)

public static boolean isFileOlder(File file, Date date) {  

            if (date == null) {  

                throw new IllegalArgumentException("No specified date");  

            }  

            return isFileOlder(file,date.getTime());  

        }  

檢測指定文件的最後修改時間(毫秒)是否在指定日期之後isFileOlder(File file, long timeMillis)

public static boolean isFileOlder(Filefile, long timeMillis) {  

        if (file == null) {  

            throw new IllegalArgumentException("No specified file");  

        }  

        if (!file.exists()) {  

            return false;  

        }  

        return file.lastModified() <timeMillis;  

    }  

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

public static long checksumCRC32(File file) throws IOException {  

            CRC32 crc = new CRC32();  

            checksum(file, crc);  

            return crc.getValue();  

        }  

計算一個文件使用指定的校驗對象的校驗checksum(Filefile, Checksum checksum)

public static Checksum checksum(File file, Checksum checksum) throws IOException {  

            if (file.isDirectory()) {  

                throw new IllegalArgumentException("Check sums can't be computed on directories");  

            }  

            InputStream in = null;  

            try {  

                in = new CheckedInputStream(newFileInputStream(file), checksum);  

                IOUtils.copy(in, newNullOutputStream());  

            } finally {  

                IOUtils.closeQuietly(in);  

            }  

            return checksum;  

        }  

移動目錄到新的目錄並且刪除老的目錄moveDirectory(File srcDir, File destDir)

public static void moveDirectory(File srcDir, File destDir) throws IOException {  

            if (srcDir == null) {  

                throw new NullPointerException("Source must not be null");  

            }  

            if (destDir == null) {  

                throw new NullPointerException("Destination must not be null");  

            }  

            if (!srcDir.exists()) {  

                throw new FileNotFoundException("Source '" + srcDir + "' does not exist");  

            }  

            if (!srcDir.isDirectory()) {  

                throw new IOException("Source '" + srcDir + "' is not a directory");  

            }  

            if (destDir.exists()) {  

                throw new FileExistsException("Destination '" + destDir + "' already exists");  

            }  

            boolean rename = srcDir.renameTo(destDir);  

            if (!rename) {  

                copyDirectory( srcDir, destDir);  

                deleteDirectory( srcDir );  

                if (srcDir.exists()) {  

                    throw new IOException("Failed to delete original directory '" + srcDir +  

                            "' after copyto '" + destDir + "'");  

                }  

            }  

        }  

把一個目錄移動到另一個目錄中去moveDirectoryToDirectory(File src, File destDir, booleancreateDestDir)

public static void moveDirectoryToDirectory(File src, File destDir, booleancreateDestDir) throws IOException {  

            if (src == null) {  

                throw new NullPointerException("Source must not be null");  

            }  

            if (destDir == null) {  

                throw new NullPointerException("Destination directory must not be null");  

            }  

            if (!destDir.exists() &&createDestDir) {  

                destDir.mkdirs();  

            }  

            if (!destDir.exists()) {  

                throw new FileNotFoundException("Destination directory '" + destDir +  

                        "' does not exist[createDestDir=" + createDestDir +"]");  

            }  

            if (!destDir.isDirectory()) {  

                throw new IOException("Destination'" + destDir + "' is not a directory");  

            }  

            moveDirectory(src, newFile(destDir, src.getName()));  



        }  

複製文件到對應的文件中去moveFile(FilesrcFile, File destFile)

public static void moveFile(File srcFile, File destFile) throws IOException {  

            if (srcFile == null) {  

                throw new NullPointerException("Source must not be null");  

            }  

            if (destFile == null) {  

                throw new NullPointerException("Destination must not be null");  

            }  

            if (!srcFile.exists()) {  

                throw new FileNotFoundException("Source '" + srcFile + "' does not exist");  

            }  

            if (srcFile.isDirectory()) {  

                throw new IOException("Source '" + srcFile + "' is a directory");  

            }  

            if (destFile.exists()) {  

                throw new FileExistsException("Destination '" + destFile + "' already exists");  

            }  

            if (destFile.isDirectory()) {  

                throw new IOException("Destination '" + destFile + "' is a directory");  

            }  

            boolean rename =srcFile.renameTo(destFile);  

            if (!rename) {  

                copyFile( srcFile, destFile );  

                if (!srcFile.delete()) {  

                   FileUtils.deleteQuietly(destFile);  

                    throw new IOException("Failed to delete original file '" + srcFile +  

                            "' after copy to '" + destFile + "'");  

                }  

            }  

        }  

複製文件到對應的文件中去,可設置當目標文件不存在時是否創建新的文件moveFile(File srcFile, File destFile)

public static void moveFileToDirectory(File srcFile, File destDir, booleancreateDestDir) throws IOException {  

            if (srcFile == null) {  

                throw new NullPointerException("Source must not be null");  

            }  

            if (destDir == null) {  

                throw new NullPointerException("Destination directory must not be null");  

            }  

            if (!destDir.exists() &&createDestDir) {  

                destDir.mkdirs();  

            }  

            if (!destDir.exists()) {  

                throw new FileNotFoundException("Destination directory '" + destDir +  

                        "' does not exist[createDestDir=" + createDestDir +"]");  

            }  

            if (!destDir.isDirectory()) {  

                throw new IOException("Destination'" + destDir + "' is not a directory");  

            }  

            moveFile(srcFile, new File(destDir,srcFile.getName()));  

        }  

移動文件或者目錄到新的路徑下,並且設置在目標路徑不存在的情況下是否創建moveToDirectory(File src, File destDir, boolean createDestDir)

public static void moveToDirectory(File src, File destDir, boolean createDestDir)throws IOException {  

           if (src == null) {  

                throw new NullPointerException("Source must not be null");  

            }  

            if (destDir == null) {  

                throw new NullPointerException("Destination must not be null");  

            }  

            if (!src.exists()) {  

                throw new FileNotFoundException("Source '" + src + "' does notexist");  

            }  

            if (src.isDirectory()) {  

                moveDirectoryToDirectory(src,destDir, createDestDir);  

            } else {  

                moveFileToDirectory(src,destDir, createDestDir);  

            }  

        }  

確定指定的文件是否是一個符號鏈接,而不是實際的文件。isSymlink(File file)

public static boolean isSymlink(File file) throws IOException {  

            if (file == null) {  

                throw new NullPointerException("File must not be null");  

            }  

            if(FilenameUtils.isSystemWindows()) {  

                return false;  

            }  

            File fileInCanonicalDir = null;  

            if (file.getParent() == null) {  

                fileInCanonicalDir = file;  

            } else {  

                File canonicalDir =file.getParentFile().getCanonicalFile();  

                fileInCanonicalDir = newFile(canonicalDir, file.getName());  

            }              if(fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())){  

                return false;  

            } else {  

                return true;  

            }  

        }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章