Java文件操作大全

jopen 10年前發布 | 22K 次閱讀 Java Java開發

一些常用的文件操作。

    package com.files.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.swing.filechooser.FileFilter;  

/** 
 * 此類中封裝一些常用的文件操作。 
 * 所有方法都是靜態方法,不需要生成此類的實例, 
 * 為避免生成此類的實例,構造方法被申明為private類型的。 
 * http://www.jq-school.com 
 * @since  1.0 
 */  

public class FileUtil {  
  /** 
   * 私有構造方法,防止類的實例化,因為工具類不需要實例化。 
   */  
  private FileUtil() {  

  }  

  /** 
   * 修改文件的最后訪問時間。 
   * 如果文件不存在則創建該文件。 
   * <b>目前這個方法的行為方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考慮中。</b> 
   * @param file 需要修改最后訪問時間的文件。 
   * @since  1.0 
   */  
  public static void touch(File file) {  
    long currentTime = System.currentTimeMillis();  
    if (!file.exists()) {  
      System.err.println("file not found:" + file.getName());  
      System.err.println("Create a new file:" + file.getName());  
      try {  
        if (file.createNewFile()) {  
          System.out.println("Succeeded!");  
        }  
        else {  
          System.err.println("Create file failed!");  
        }  
      }  
      catch (IOException e) {  
        System.err.println("Create file failed!");  
        e.printStackTrace();  
      }  
    }  
    boolean result = file.setLastModified(currentTime);  
    if (!result) {  
      System.err.println("touch failed: " + file.getName());  
    }  
  }  

  /** 
   * 修改文件的最后訪問時間。 
   * 如果文件不存在則創建該文件。 
   * <b>目前這個方法的行為方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考慮中。</b> 
   * @param fileName 需要修改最后訪問時間的文件的文件名。 
   * @since  1.0 
   */  
  public static void touch(String fileName) {  
    File file = new File(fileName);  
    touch(file);  
  }  

  /** 
   * 修改文件的最后訪問時間。 
   * 如果文件不存在則創建該文件。 
   * <b>目前這個方法的行為方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考慮中。</b> 
   * @param files 需要修改最后訪問時間的文件數組。 
   * @since  1.0 
   */  
  public static void touch(File[] files) {  
    for (int i = 0; i < files.length; i++) {  
      touch(files[i]);  
    }  
  }  

  /** 
   * 修改文件的最后訪問時間。 
   * 如果文件不存在則創建該文件。 
   * <b>目前這個方法的行為方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考慮中。</b> 
   * @param fileNames 需要修改最后訪問時間的文件名數組。 
   * @since  1.0 
   */  
  public static void touch(String[] fileNames) {  
    File[] files = new File[fileNames.length];  
    for (int i = 0; i < fileNames.length; i++) {  
      files[i] = new File(fileNames[i]);  
    }  
    touch(files);  
  }  

  /** 
   * 判斷指定的文件是否存在。 
   * @param fileName 要判斷的文件的文件名 
   * @return 存在時返回true,否則返回false。 
   * @since  1.0 
   */  
  public static boolean isFileExist(String fileName) {  
    return new File(fileName).isFile();  
  }  

  /** 
   * 創建指定的目錄。 
   * 如果指定的目錄的父目錄不存在則創建其目錄書上所有需要的父目錄。 
   * <b>注意:可能會在返回false的時候創建部分父目錄。</b> 
   * @param file 要創建的目錄 
   * @return 完全創建成功時返回true,否則返回false。 
   * @since  1.0 
   */  
  public static boolean makeDirectory(File file) {  
    File parent = file.getParentFile();  
    if (parent != null) {  
      return parent.mkdirs();  
    }  
    return false;  
  }  

  /** 
   * 創建指定的目錄。 
   * 如果指定的目錄的父目錄不存在則創建其目錄書上所有需要的父目錄。 
   * <b>注意:可能會在返回false的時候創建部分父目錄。</b> 
   * @param fileName 要創建的目錄的目錄名 
   * @return 完全創建成功時返回true,否則返回false。 
   * @since  1.0 
   */  
  public static boolean makeDirectory(String fileName) {  
    File file = new File(fileName);  
    return makeDirectory(file);  
  }  

  /** 
   * 清空指定目錄中的文件。 
   * 這個方法將盡可能刪除所有的文件,但是只要有一個文件沒有被刪除都會返回false。 
   * 另外這個方法不會迭代刪除,即不會刪除子目錄及其內容。 
   * @param directory 要清空的目錄 
   * @return 目錄下的所有文件都被成功刪除時返回true,否則返回false. 
   * @since  1.0 
   */  
  public static boolean emptyDirectory(File directory) {  
    boolean result = true;  
    File[] entries = directory.listFiles();  
    for (int i = 0; i < entries.length; i++) {  
      if (!entries[i].delete()) {  
        result = false;  
      }  
    }  
    return result;  
  }  

  /** 
   * 清空指定目錄中的文件。 
   * 這個方法將盡可能刪除所有的文件,但是只要有一個文件沒有被刪除都會返回false。 
   * 另外這個方法不會迭代刪除,即不會刪除子目錄及其內容。 
   * @param directoryName 要清空的目錄的目錄名 
   * @return 目錄下的所有文件都被成功刪除時返回true,否則返回false。 
   * @since  1.0 
   */  
  public static boolean emptyDirectory(String directoryName) {  
    File dir = new File(directoryName);  
    return emptyDirectory(dir);  
  }  

  /** 
   * 刪除指定目錄及其中的所有內容。 
   * @param dirName 要刪除的目錄的目錄名 
   * @return 刪除成功時返回true,否則返回false。 
   * @since  1.0 
   */  
  public static boolean deleteDirectory(String dirName) {  
    return deleteDirectory(new File(dirName));  
  }  

  /** 
   * 刪除指定目錄及其中的所有內容。 
   * @param dir 要刪除的目錄 
   * @return 刪除成功時返回true,否則返回false。 
   * @since  1.0 
   */  
  public static boolean deleteDirectory(File dir) {  
    if ( (dir == null) || !dir.isDirectory()) {  
      throw new IllegalArgumentException("Argument " + dir +  
                                         " is not a directory. ");  
    }  

    File[] entries = dir.listFiles();  
    int sz = entries.length;  

    for (int i = 0; i < sz; i++) {  
      if (entries[i].isDirectory()) {  
        if (!deleteDirectory(entries[i])) {  
          return false;  
        }  
      }  
      else {  
        if (!entries[i].delete()) {  
          return false;  
        }  
      }  
    }  

    if (!dir.delete()) {  
      return false;  
    }  
    return true;  
  }  

  /** 
   * 列出目錄中的所有內容,包括其子目錄中的內容。 
   * @param fileName 要列出的目錄的目錄名 
   * @return 目錄內容的文件數組。 
   * @since  1.0 
   */  
  /*public static File[] listAll(String fileName) { 
    return listAll(new File(fileName)); 
  }*/  

  /** 
   * 列出目錄中的所有內容,包括其子目錄中的內容。 
   * @param file 要列出的目錄 
   * @return 目錄內容的文件數組。 
   * @since  1.0 
   */  
  /*public static File[] listAll(File file) { 
    ArrayList list = new ArrayList(); 
    File[] files; 
    if (!file.exists() || file.isFile()) { 
      return null; 
    } 
    list(list, file, new AllFileFilter()); 
    list.remove(file); 
    files = new File[list.size()]; 
    list.toArray(files); 
    return files; 
  }*/  

  /** 
   * 列出目錄中的所有內容,包括其子目錄中的內容。 
   * @param file 要列出的目錄 
   * @param filter 過濾器 
   * @return 目錄內容的文件數組。 
   * @since  1.0 
   */  
  public static File[] listAll(File file,  
                               javax.swing.filechooser.FileFilter filter) {  
    ArrayList list = new ArrayList();  
    File[] files;  
    if (!file.exists() || file.isFile()) {  
      return null;  
    }  
    list(list, file, filter);  
    files = new File[list.size()];  
    list.toArray(files);  
    return files;  
  }  

  /** 
   * 將目錄中的內容添加到列表。 
   * @param list 文件列表 
   * @param filter 過濾器 
   * @param file 目錄 
   */  
  private static void list(ArrayList list, File file,  
                           javax.swing.filechooser.FileFilter filter) {  
    if (filter.accept(file)) {  
      list.add(file);  
      if (file.isFile()) {  
        return;  
      }  
    }  
    if (file.isDirectory()) {  
      File files[] = file.listFiles();  
      for (int i = 0; i < files.length; i++) {  
        list(list, files[i], filter);  
      }  
    }  

  }  

  /** 
   * 返回文件的URL地址。 
   * @param file 文件 
   * @return 文件對應的的URL地址 
   * @throws MalformedURLException 
   * @since  1.0 
   * @deprecated 在實現的時候沒有注意到File類本身帶一個toURL方法將文件路徑轉換為URL。 
   *             請使用File.toURL方法。 
   */  
  public static URL getURL(File file) throws MalformedURLException {  
    String fileURL = "file:/" + file.getAbsolutePath();  
    URL url = new URL(fileURL);  
    return url;  
  }  

  /** 
   * 從文件路徑得到文件名。 
   * @param filePath 文件的路徑,可以是相對路徑也可以是絕對路徑 
   * @return 對應的文件名 
   * @since  1.0 
   */  
  public static String getFileName(String filePath) {  
    File file = new File(filePath);  
    return file.getName();  
  }  

  /** 
   * 從文件名得到文件絕對路徑。 
   * @param fileName 文件名 
   * @return 對應的文件路徑 
   * @since  1.0 
   */  
  public static String getFilePath(String fileName) {  
    File file = new File(fileName);  
    return file.getAbsolutePath();  
  }  

  /** 
   * 將DOS/Windows格式的路徑轉換為UNIX/Linux格式的路徑。 
   * 其實就是將路徑中的"\"全部換為"/",因為在某些情況下我們轉換為這種方式比較方便, 
   * 某中程度上說"/"比"\"更適合作為路徑分隔符,而且DOS/Windows也將它當作路徑分隔符。 
   * @param filePath 轉換前的路徑 
   * @return 轉換后的路徑 
   * @since  1.0 
   */  
  public static String toUNIXpath(String filePath) {  
    return filePath.replace('\\', '/');  
  }  

  /** 
   * 從文件名得到UNIX風格的文件絕對路徑。 
   * @param fileName 文件名 
   * @return 對應的UNIX風格的文件路徑 
   * @since  1.0 
   * @see #toUNIXpath(String filePath) toUNIXpath 
   */  
  public static String getUNIXfilePath(String fileName) {  
    File file = new File(fileName);  
    return toUNIXpath(file.getAbsolutePath());  
  }  

  /** 
   * 得到文件的類型。 
   * 實際上就是得到文件名中最后一個“.”后面的部分。 
   * @param fileName 文件名 
   * @return 文件名中的類型部分 
   * @since  1.0 
   */  
  public static String getTypePart(String fileName) {  
    int point = fileName.lastIndexOf('.');  
    int length = fileName.length();  
    if (point == -1 || point == length - 1) {  
      return "";  
    }  
    else {  
      return fileName.substring(point + 1, length);  
    }  
  }  

  /** 
   * 得到文件的類型。 
   * 實際上就是得到文件名中最后一個“.”后面的部分。 
   * @param file 文件 
   * @return 文件名中的類型部分 
   * @since  1.0 
   */  
  public static String getFileType(File file) {  
    return getTypePart(file.getName());  
  }  

  /** 
   * 得到文件的名字部分。 
   * 實際上就是路徑中的最后一個路徑分隔符后的部分。 
   * @param fileName 文件名 
   * @return 文件名中的名字部分 
   * @since  1.0 
   */  
  public static String getNamePart(String fileName) {  
    int point = getPathLsatIndex(fileName);  
    int length = fileName.length();  
    if (point == -1) {  
      return fileName;  
    }  
    else if (point == length - 1) {  
      int secondPoint = getPathLsatIndex(fileName, point - 1);  
      if (secondPoint == -1) {  
        if (length == 1) {  
          return fileName;  
        }  
        else {  
          return fileName.substring(0, point);  
        }  
      }  
      else {  
        return fileName.substring(secondPoint + 1, point);  
      }  
    }  
    else {  
      return fileName.substring(point + 1);  
    }  
  }  

  /** 
   * 得到文件名中的父路徑部分。 
   * 對兩種路徑分隔符都有效。 
   * 不存在時返回""。 
   * 如果文件名是以路徑分隔符結尾的則不考慮該分隔符,例如"/path/"返回""。 
   * @param fileName 文件名 
   * @return 父路徑,不存在或者已經是父目錄時返回"" 
   * @since  1.0 
   */  
  public static String getPathPart(String fileName) {  
    int point = getPathLsatIndex(fileName);  
    int length = fileName.length();  
    if (point == -1) {  
      return "";  
    }  
    else if (point == length - 1) {  
      int secondPoint = getPathLsatIndex(fileName, point - 1);  
      if (secondPoint == -1) {  
        return "";  
      }  
      else {  
        return fileName.substring(0, secondPoint);  
      }  
    }  
    else {  
      return fileName.substring(0, point);  
    }  
  }  

  /** 
   * 得到路徑分隔符在文件路徑中首次出現的位置。 
   * 對于DOS或者UNIX風格的分隔符都可以。 
   * @param fileName 文件路徑 
   * @return 路徑分隔符在路徑中首次出現的位置,沒有出現時返回-1。 
   * @since  1.0 
   */  
  public static int getPathIndex(String fileName) {  
    int point = fileName.indexOf('/');  
    if (point == -1) {  
      point = fileName.indexOf('\\');  
    }  
    return point;  
  }  

  /** 
   * 得到路徑分隔符在文件路徑中指定位置后首次出現的位置。 
   * 對于DOS或者UNIX風格的分隔符都可以。 
   * @param fileName 文件路徑 
   * @param fromIndex 開始查找的位置 
   * @return 路徑分隔符在路徑中指定位置后首次出現的位置,沒有出現時返回-1。 
   * @since  1.0 
   */  
  public static int getPathIndex(String fileName, int fromIndex) {  
    int point = fileName.indexOf('/', fromIndex);  
    if (point == -1) {  
      point = fileName.indexOf('\\', fromIndex);  
    }  
    return point;  
  }  

  /** 
   * 得到路徑分隔符在文件路徑中最后出現的位置。 
   * 對于DOS或者UNIX風格的分隔符都可以。 
   * @param fileName 文件路徑 
   * @return 路徑分隔符在路徑中最后出現的位置,沒有出現時返回-1。 
   * @since  1.0 
   */  
  public static int getPathLsatIndex(String fileName) {  
    int point = fileName.lastIndexOf('/');  
    if (point == -1) {  
      point = fileName.lastIndexOf('\\');  
    }  
    return point;  
  }  

  /** 
   * 得到路徑分隔符在文件路徑中指定位置前最后出現的位置。 
   * 對于DOS或者UNIX風格的分隔符都可以。 
   * @param fileName 文件路徑 
   * @param fromIndex 開始查找的位置 
   * @return 路徑分隔符在路徑中指定位置前最后出現的位置,沒有出現時返回-1。 
   * @since  1.0 
   */  
  public static int getPathLsatIndex(String fileName, int fromIndex) {  
    int point = fileName.lastIndexOf('/', fromIndex);  
    if (point == -1) {  
      point = fileName.lastIndexOf('\\', fromIndex);  
    }  
    return point;  
  }  

  /** 
   * 將文件名中的類型部分去掉。 
   * @param filename 文件名 
   * @return 去掉類型部分的結果 
   * @since  1.0 
   */  
  public static String trimType(String filename) {  
    int index = filename.lastIndexOf(".");  
    if (index != -1) {  
      return filename.substring(0, index);  
    }  
    else {  
      return filename;  
    }  
  }  
  /** 
   * 得到相對路徑。 
   * 文件名不是目錄名的子節點時返回文件名。 
   * @param pathName 目錄名 
   * @param fileName 文件名 
   * @return 得到文件名相對于目錄名的相對路徑,目錄下不存在該文件時返回文件名 
   * @since  1.0 
   */  
  public static String getSubpath(String pathName,String fileName) {  
    int index = fileName.indexOf(pathName);  
    if (index != -1) {  
      return fileName.substring(index + pathName.length() + 1);  
    }  
    else {  
      return fileName;  
    }  
  }  

  /** 
   * 檢查給定目錄的存在性 
   * 保證指定的路徑可用,如果指定的路徑不存在,那么建立該路徑,可以為多級路徑 
   * @param path 
   * @return 真假值 
   * @since  1.0 
   */  
   public static final boolean pathValidate(String path)  
   {  
     //String path="d:/web/www/sub";  
     //System.out.println(path);  
     //path = getUNIXfilePath(path);  

     //path = ereg_replace("^\\/+", "", path);  
     //path = ereg_replace("\\/+$", "", path);  
     String[] arraypath = path.split("/");  
     String tmppath = "";  
     for (int i = 0; i < arraypath.length; i++)  
     {  
       tmppath += "/" + arraypath[i];  
       File d = new File(tmppath.substring(1));  
       if (!d.exists()) { //檢查Sub目錄是否存在  
           System.out.println(tmppath.substring(1));  
         if (!d.mkdir())  
         {  
           return false;  
         }  
       }  
     }  
     return true;  
   }  

   /** 
    * 讀取文件的內容 
    * 讀取指定文件的內容 
    * @param path 為要讀取文件的絕對路徑 
    * @return 以行讀取文件后的內容。 
    * @since  1.0 
    */  
   public static final String getFileContent(String path) throws IOException  
   {  
     String filecontent = "";  
     try {  
       File f = new File(path);  
       if (f.exists()) {  
         FileReader fr = new FileReader(path);  
         BufferedReader br = new BufferedReader(fr); //建立BufferedReader對象,并實例化為br  
         String line = br.readLine(); //從文件讀取一行字符串  
         //判斷讀取到的字符串是否不為空  
         while (line != null) {  
           filecontent += line + "\n";  
           line = br.readLine(); //從文件中繼續讀取一行數據  
         }  
         br.close(); //關閉BufferedReader對象  
         fr.close(); //關閉文件  
       }  

     }  
     catch (IOException e) {  
       throw e;  
     }  
     return filecontent;  
   }  

   /** 
    * 根據內容生成文件 
    * @param path要生成文件的絕對路徑, 
    * @param 文件的內容。 
    * @return 真假值 
    * @since  1.0 
    */  
   public static final boolean genModuleTpl(String path, String modulecontent)  throws IOException  
   {  

     path = getUNIXfilePath(path);  
     String[] patharray = path.split("\\/");  
     String modulepath = "";  
     for (int i = 0; i < patharray.length - 1; i++) {  
       modulepath += "/" + patharray[i];  
     }  
     File d = new File(modulepath.substring(1));  
     if (!d.exists()) {  
       if (!pathValidate(modulepath.substring(1))) {  
         return false;  
       }  
     }  
     try {  
       FileWriter fw = new FileWriter(path); //建立FileWriter對象,并實例化fw  
       //將字符串寫入文件  
       fw.write(modulecontent);  
       fw.close();  
     }  
     catch (IOException e) {  
       throw e;  
     }  
     return true;  
   }  

   /** 
    * 獲取圖片文件的擴展名(發布系統專用) 
    * @param picname 為圖片名稱加上前面的路徑不包括擴展名 
    * @return 圖片的擴展名 
    * @since  1.0 
    */  
   public static final String getPicExtendName(String pic_path)  
   {  
     pic_path = getUNIXfilePath(pic_path);  
     String pic_extend = "";  
     if (isFileExist(pic_path + ".gif"))  
     {  
       pic_extend = ".gif";  
     }  
     if (isFileExist(pic_path + ".jpeg"))  
     {  
       pic_extend = ".jpeg";  
     }  
     if (isFileExist(pic_path + ".jpg"))  
     {  
       pic_extend = ".jpg";  
     }  
     if (isFileExist(pic_path + ".png"))  
     {  
       pic_extend = ".png";  
     }  
     return pic_extend; //返回圖片擴展名  
   }  
   //拷貝文件  
   public static final boolean CopyFile(File in, File out) throws Exception {  
       try {  
           FileInputStream fis = new FileInputStream(in);  
           FileOutputStream fos = new FileOutputStream(out);  
           byte[] buf = new byte[1024];  
           int i = 0;  
           while ((i = fis.read(buf)) != -1) {  
               fos.write(buf, 0, i);  
           }  
           fis.close();  
           fos.close();  
           return true;  
       } catch (IOException ie) {  
           ie.printStackTrace();  
           return false;  
       }  
   }  
   //拷貝文件  
   public static final boolean CopyFile(String infile, String outfile) throws Exception {  
       try {  
           File in = new File(infile);  
           File out = new File(outfile);  
           return CopyFile(in, out);  
       } catch (IOException ie) {  
           ie.printStackTrace();  
           return false;  
       }  

   }  
   /** 
    * 計算圖片數量 
    * @param id 
    * @param dtime 
    * @return 
    */  
   public static final int countPics(String id,String dtime,String extensions){  
       int counts = 0;   

       MyFileFilter mfilter = new MyFileFilter(extensions.split(","));  
       PropsUtil pu = new PropsUtil();  
       String PICROOT = pu.readSingleProps("DestinationsPICROOT").trim();  
       String path = PICROOT + "/"+dtime.substring(0, 10) + "/";  
       File lfile = new File(path);  
       String filename;  
       if(lfile.isDirectory()){  
           File[] files = lfile.listFiles(mfilter);  
           for(int i=0;i<files.length;i++){  
               filename = files[i].getName();  
               if((filename.indexOf(id + "_")==0)&&(filename.indexOf("_small")>-1))  
                   counts ++;  
           }  
           files = null;  
       }  
       filename = null;  
       lfile = null;  
       pu = null;  
       mfilter = null;  

       return counts;  
   }  

}  </pre>
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!