1. 程式人生 > >Java File類總結和FileUtils類

Java File類總結和FileUtils類

複製程式碼
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      
http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.
*/ package com.mengdd.file; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /* * FileUtils copied from org.apache.commons.io.FileUtils */ public class FileUtils { /** * Construct a file from the set of name elements. * *
@param directory * the parent directory * @param names * the name elements * @return the file */ public static File getFile(File directory, String... names) { if (directory == null) { throw new NullPointerException( "directorydirectory must not be null"); } if (names == null) { throw new NullPointerException("names must not be null"); } File file = directory; for (String name : names) { file = new File(file, name); } return file; } /** * Construct a file from the set of name elements. * * @param names * the name elements * @return the file */ public static File getFile(String... names) { if (names == null) { throw new NullPointerException("names must not be null"); } File file = null; for (String name : names) { if (file == null) { file = new File(name); } else { file = new File(file, name); } } return file; } /** * Opens a {@link FileInputStream} for the specified file, providing better * error messages than simply calling <code>new FileInputStream(file)</code> * . * <p> * At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. * <p> * An exception is thrown if the file does not exist. An exception is thrown * if the file object exists but is a directory. An exception is thrown if * the file exists but cannot be read. * * @param file * the file to open for input, must not be {@code null} * @return a new {@link FileInputStream} for the specified file * @throws FileNotFoundException * if the file does not exist * @throws IOException * if the file object is a directory * @throws IOException * if the file cannot be read */ public static FileInputStream openInputStream(File file) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canRead() == false) { throw new IOException("File '" + file + "' cannot be read"); } } else { throw new FileNotFoundException("File '" + file + "' does not exist"); } return new FileInputStream(file); } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * <p> * At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. * <p> * The parent directory will be created if it does not exist. The file will * be created if it does not exist. An exception is thrown if the file * object exists but is a directory. An exception is thrown if the file * exists but cannot be written to. An exception is thrown if the parent * directory cannot be created. * * @param file * the file to open for output, must not be {@code null} * @param append * if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @return a new {@link FileOutputStream} for the specified file * @throws IOException * if the file object is a directory * @throws IOException * if the file cannot be written to * @throws IOException * if a parent directory needs creating but that fails */ public static FileOutputStream openOutputStream(File file, boolean append) 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) { if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException("Directory '" + parent + "' could not be created"); } } } return new FileOutputStream(file, append); } public static FileOutputStream openOutputStream(File file) throws IOException { return openOutputStream(file, false); } /** * Cleans a directory without deleting it. * * @param directory * directory to clean * @throws IOException * in case cleaning is unsuccessful */ 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; } } // ----------------------------------------------------------------------- /** * Deletes a directory recursively. * * @param directory * directory to delete * @throws IOException * in case deletion is unsuccessful */ public static void deleteDirectory(File directory) throws IOException { if (!directory.exists()) { return; } cleanDirectory(directory); if (!directory.delete()) { String message = "Unable to delete directory " + directory + "."; throw new IOException(message); } } /** * Deletes a file. If file is a directory, delete it and all * sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>You get exceptions when a file or directory cannot be deleted. * (java.io.File methods returns a boolean)</li> * </ul> * * @param file * file or directory to delete, must not be {@code null} * @throws NullPointerException * if the directory is {@code null} * @throws FileNotFoundException * if the file was not found * @throws IOException * in case deletion is unsuccessful */ 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 delete file: " + file; throw new IOException(message); } } } /** * Deletes a file, never throwing an exception. If file is a directory, * delete it and all sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * * @param file * file or directory to delete, can be {@code null} * @return {@code true} if the file or directory was deleted, otherwise * {@code false} * */ 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; } } /** * Makes a directory, including any necessary but nonexistent parent * directories. If a file already exists with specified name but it is * not a directory then an IOException is thrown. * If the directory cannot be created (or does not already exist) * then an IOException is thrown. * * @param directory * directory to create, must not be {@code null} * @throws NullPointerException * if the directory is {@code null} * @throws IOException * if the directory cannot be created or the file already exists * but is not a directory */ public static void forceMkdir(File directory) throws IOException { if (directory.exists()) { if (!directory.isDirectory()) { String message = "File " + directory + " exists and is " + "not a directory. Unable to create directory."; throw new IOException(message); } } else { if (!directory.mkdirs()) { // Double-check that some other thread or process hasn't made // the directory in the background if (!directory.isDirectory()) { String message = "Unable to create directory " + directory; throw new IOException(message); } } } } /** * Returns the size of the specified file or directory. If the provided * {@link File} is a regular file, then the file's length is returned. * If the argument is a directory, then the size of the directory is * calculated recursively. If a directory or subdirectory is security * restricted, its size will not be included. * * @param file * the regular file or directory to return the size * of (must not be {@code null}). * * @return the length of the file, or recursive size of the directory, * provided (in bytes). * * @throws NullPointerException * if the file is {@code null} * @throws IllegalArgumentException * if the file does not exist. * */ 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(); } } /** * Counts the size of a directory recursively (sum of the length of all * files). * * @param directory * directory to inspect, must not be {@code null} * @return size of directory in bytes, 0 if directory is security * restricted, a negative number when the real total * is greater than {@link Long#MAX_VALUE}. * @throws NullPointerException * if the directory is {@code null} */ public static long sizeOfDirectory(File directory) { checkDirectory(directory); final File[] files = directory.listFiles(); if (files == null) { // null if security restricted return 0L; } long size = 0; for (final File file : files) { size += sizeOf(file); if (size < 0) { break; } } return size; } /** * Checks that the given {@code File} exists and is a directory. * * @param directory * The {@code File} to check. * @throws IllegalArgumentException * if the given {@code File} does not exist or is not a * directory. */ private static void checkDirectory(File directory) { if (!directory.exists()) { throw new IllegalArgumentException(directory + " does not exist"); } if (!directory.isDirectory()) { throw new IllegalArgumentException(directory + " is not a directory"); } } }

相關推薦

Java File總結FileUtils

/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this

Java中接口抽象的比較

系列 分享 space 日誌信息 pub 指向 相關 最好的 就會 Java中接口和抽象類的比較-2013年5月寫的讀書筆記摘要 1. 概述 接口(Interface)和抽象類(abstract class)是 Java 語言中支持抽象類的兩種機制,是

Java】基本引用型(值傳遞)

適合 and span print pri right bre enc this 【關鍵詞】 【問題】 · 加深對基本類型和引用類型的理解; 【效果圖】 【分析】 參見最後的【參考資料】 【解決方式】 【代碼】 public

(轉載)深入理解java的接口抽象

final類 轉載 如何實現 靜態 參考 種類型 tar 發現 是否 本文轉自地址:http://www.cnblogs.com/dolphin0520/p/3811437.html 作者:海子 出處:http://www.cnblogs.com/dolphin0520/

java基本數據包裝之間的區別

oat 基本 null 使用方式 賦值 通過 border 之間 wid 1.聲明方式不同,基本類型不適用new關鍵字,而包裝類型需要使用new關鍵字來在堆中分配存儲空間; 2.存儲方式及位置不同,基本類型是直接將變量值存儲在堆棧中,而包裝類型是將對象放在堆中,然後通過引用

Java中的基本引用型變量的區別

new jre ear ref 數據 這一 對象類型 完成 值傳遞 基本類型: 基本類型自然不用說了,它的值就是一個數字,一個字符或一個布爾值。 引用類型: 是一個對象類型,值是什麽呢?它的值是指向內存空間的引用,就是地址,所指向的內存中保存著變量所表示的一個值或一組

深入理解Java的接口抽象

blog 編譯 但是 單獨 設計者 錯誤 了解 strac 函數 轉載請標明原文鏈接: http://www.cnblogs.com/dolphin0520/p/3811437.html 對於面向對象編程來說,抽象是它的一大特征之一。在Java中,可以通過兩種形式來體

h5棋牌源碼租用Java的MD5加密解密

哈希函數 網絡問題 pri rgs update array 重要 和數 下載 理解MD5MD5的應用非常廣泛h5棋牌源碼租用(h5.hxforum.com)聯系170618633533企鵝2952777280(http://yhgj8004.com)源碼出售 房卡出售

【IO流】31 - commons工具----FilenameUtilsFileUtils

tostring date cas 獲取 copy 文件 判斷 filename mon FilenameUtils package cn.itcast.demo3; import org.apache.commons.io.FilenameUtils; pub

深入理解Java的接口抽象(轉)

protected 創建對象 使用 很多 抽象方法 wid 類的抽象 con 模板 深入理解Java的接口和抽象類   對於面向對象編程來說,抽象是它的一大特征之一。在Java中,可以通過兩種形式來體現OOP的抽象:接口和抽象類。這兩者有太多相似的地方,又有太多不同的地方。

Java內存分配String型的深度解析

ann img 解析 線程的狀態 離開 log gen 對象創建 內存分區 一、引題 在java語言的所有數據類型中,String類型是比較特殊的一種類型,同時也是面試的時候經常被問到的一個知識點,本文結合java內存分配深度分析關於String的許多令人迷惑的問題。下面是

JAVA引用型的區別

回收 attribute 布爾類型 tor main ava 引用 接口類 test java這兩種數據類型分別有哪些? java 中的數據類型分為兩大類:值類型(基本數據類型)和引用類型(復合數據類型) 一:值類型:   整數類型(byte,short,int,long)

Java中的基本包裝

屬性和方法 bject 關鍵字 map 基本類型 idt arr 通過 clas Java中基本數據類型與包裝類型有 基本類型 包裝器類型 boolean Boolean char Character int Integer byte

java中,方法參數是基本引用型的區別

關系 傳遞 類型 參數 變量 找到 外部 內存地址 chan 方法參數是基本類型時,傳遞的是值。 方法參數是引用類型時,傳遞的是內存地址值 當參數是基本類型時,在調用方法時將值傳遞到方法中,運行方法,運行結束方法退出,對原本main中定義的變量沒有任何操作(方法中沒有re

java中的時間日期

日期、時間類 Date類 java8中的構造器,之前有六個但是其餘四個已經不推薦使用了。 構造器 功能 Date() 生成一個代表當前日期時間的Date物件

java介面抽象的區別

全域性變數的區別 介面中所有的全域性變數預設為 public static final,處於方法區的常量池中,且是靜態域中的成員 抽象類的全域性變數無硬性約束 方法的區別 介面 介面

Java——模板設計模式列舉的實現

嘗試以MarkdownPad2方式寫部落格,感覺十分有條理,第一次使用花的時間較長,但是熟能生巧,後面會越用越熟練,更快吧~ 1. 模板設計模式 (1).模板方法模式就是定義一個演算法的骨架,而將具體的演算法延遲到子類來實現 (2)優點:使用模板方法模式

如何在Java中選擇介面抽象

什麼是抽象類? 摘要意味著某些東西不是完全具體的 - 它只是一個想法或某事的要點。因此,當我們討論抽象類時,它意味著一個本身沒有具體實現的類。這只是為其他具體類建立的結構或指南。我們可以說抽象類是具體類的靈魂。這就是我們“擴充套件”抽象類的原因。抽象類應該只有那些屬性和方法,沒有它們就不能存在具體的類。

java隨機數 Math.random Random

java實現隨機數有兩種方式1)Math.random()和Random類方法,我簡單記錄一下,方便自己回顧,更希望幫助他人。 Math.random() 這個方法是Math類提供的方法,用來返回一個處於0-1之間的浮點數。 用處: 1.返回一個位於0--1隨機

Java基礎——基本型別包裝、基本型別字串之間的轉換

基本型別和包裝類之間的轉換 基本型別和包裝類之間經常需要互相轉換,以 Integer 為例(其他幾個包裝類的操作雷同哦): 在 JDK1.5 引入自動裝箱和拆箱的機制後,包裝類和基本型別之間的轉換就更加輕鬆便利了。 那什麼是裝箱和拆箱呢?我們分別來看下 裝箱:把基本型別轉換成包裝類,使其具有物件的