File的一些小工具

package com.sinosoft.core.common.util.authority; java

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random; 數組

/**
 * 提供各類對文件系統進行操做的工具. <br>
 * 在應用程序中,常常須要對文件系統進行操做,例如複製、移動、刪除文件,查找文件的路徑,對文件進行寫操做等, 類FileUtils提供了與此相關的各類工具。
 */
public class FileUtils {
private static final File POOL_FILE = getUniqueFile(FileUtils.class,".deletefiles"); private static ArrayList deleteFilesPool;
 static {
  try {
   initPool();
  } catch (Exception e) {
   e.printStackTrace();
  }
 } app

 /**
  * 讀出之前未刪除的文件列表
  *
  * @throws Exception
  * @throws IOException
  */
 private static void initPool() {
  if (POOL_FILE.exists() && POOL_FILE.canRead()) {
   try {
    ObjectInputStream in = new ObjectInputStream(
      new FileInputStream(POOL_FILE));
    deleteFilesPool = (ArrayList) in.readObject();
    in.close();
   } catch (Exception e) {
    deleteFilesPool = new ArrayList();
   }
  } else {
   deleteFilesPool = new ArrayList();
  } dom

 } 工具

 /**
  * 構造方法,禁止實例化
  */
 private FileUtils() {
 } url

 /**
  * 複製文件. <br>
  * <br>
  * <b>示例: </b>
  *
  * <pre>
  * FileUtils.copyFile(&quot;/home/app/config.xml&quot;, &quot;/home/appbak/config_bak.xml&quot;)
  * </pre>
  *
  * @param fromFile
  *            源文件,包括完整的絕對路徑和文件名
  * @param toFile
  *            目標文件,包括完整的絕對路徑和文件名,目標路徑必須已經存在,該方法不負責建立新的目錄
  * @throws IOException
  *             拋出IOException
  */
 public static void copyFile(String fromFile, String toFile)
   throws IOException {
  FileInputStream in = new FileInputStream(fromFile);
  FileOutputStream out = new FileOutputStream(toFile);
  byte b[] = new byte[1024];
  int len;
  while ((len = in.read(b)) != -1) {
   out.write(b, 0, len);
  }
  out.close();
  in.close();
 } spa

 /**
  * 獲得短文件名. <br>
  * <br>
  * <b>示例: </b> <br>
  * FileUtils.getShortFileName(&quot;/home/app/config.xml&quot;) 返回
  * &quot;config.xml&quot;
  * FileUtils.getShortFileName(&quot;C:\\test\\config.xml&quot;) 返回
  * &quot;config.xml&quot;</br>
  *
  * @param fileName
  *            文件名
  * @return 短文件名
  */
 public static String getShortFileName(String fileName) {
  String shortFileName = "";
  int pos = fileName.lastIndexOf('\\');
  if (pos == -1) {
   pos = fileName.lastIndexOf('/');
  }
  if (pos > -1) {
   shortFileName = fileName.substring(pos + 1);
  } else {
   shortFileName = fileName;
  }
  return shortFileName;
 } .net

 /**
  * 獲得不帶擴展名的短文件名. <br>
  * <br>
  * <b>示例: </b> <br>
  * FileUtils.getShortFileNameWithoutExt(&quot;/home/app/config.xml&quot;) 返回
  * &quot;config&quot;<br>
  * FileUtils.getShortFileNameWithoutExt(&quot;C:\\test\\config.xml&quot;) 返回
  * &quot;config&quot;</br>
  *
  * @param fileName
  *            文件名
  * @return 短文件名
  */
 public static String getShortFileNameWithoutExt(String fileName) {
  String shortFileName = getShortFileName(fileName);
  shortFileName = getFileNameWithoutExt(shortFileName);
  return shortFileName;
 } xml

 /**
  * 獲得文件內容
  *
  * @param fileName
  *            文件名稱
  * @return 文件內容
  * @throws Exception
  */
 public static String read(String fileName) throws Exception {
  String fileContent = "";
  fileContent = read(new FileInputStream(fileName));
  return fileContent;
 } 對象

 /**
  * 獲得文件內容
  *
  * @param file
  *            文件
  * @return 文件內容
  * @throws Exception
  */
 public static String read(File file) throws Exception {
  String fileContent = "";
  fileContent = read(new FileInputStream(file));
  return fileContent;
 }

 /**
  * 獲得輸入流的內容
  *
  * @param is
  *            輸入流
  * @return 字符串
  * @throws Exception
  */
 public static String read(InputStream is) throws Exception {
  byte[] result = readBytes(is);
  return new String(result);
 }

 /**
  * 以byte數組方式獲得輸入流的內容
  *
  * @param fileName
  *            文件名稱
  * @return byte數組
  * @throws Exception
  */
 public static byte[] readBytes(String fileName) throws Exception {
  return readBytes(new FileInputStream(fileName));
 }

 /**
  * 以byte數組方式獲得輸入流的內容
  *
  * @param file
  *            文件
  * @return byte數組
  * @throws Exception
  */
 public static byte[] readBytes(File file) throws Exception {
  return readBytes(new FileInputStream(file));
 }

 /**
  * 以byte數組方式獲得輸入流的內容
  *
  * @param is
  *            輸入流
  * @return byte數組
  * @throws Exception
  */
 public static byte[] readBytes(InputStream is) throws Exception {
  if (is == null || is.available() < 1) {
   return new byte[0];
  }
  byte[] buff = new byte[8192];
  byte[] result = new byte[is.available()];
  int nch;
  BufferedInputStream in = new BufferedInputStream(is);
  int pos = 0;
  while ((nch = in.read(buff, 0, buff.length)) != -1) {
   System.arraycopy(buff, 0, result, pos, nch);
   pos += nch;
  }
  in.close();
  return result;
 }

 /**
  * 寫文件
  *
  * @param content
  *            文件內容
  * @param file
  *            文件對象
  * @throws IOException
  */
 public static void write(String content, File file) throws IOException {
  write(content.getBytes(), file);
 }

 /**
  * 寫文件
  *
  * @param content
  *            文件內容
  * @param file
  *            文件名
  * @throws IOException
  */
 public static void write(String content, String file) throws IOException {
  write(content, new File(file));
 }

 /**
  * 寫文件
  *
  * @param bytes
  *            文件內容
  * @param file
  *            文件名
  * @throws IOException
  */
 public static void write(byte[] bytes, String file) throws IOException {
  write(bytes, new File(file));
 }

 /**
  * 寫文件
  *
  * @param bytes
  *            文件內容
  * @param file
  *            文件
  * @throws IOException
  */
 public static void write(byte[] bytes, File file) throws IOException {
  FileOutputStream out = new FileOutputStream(file);
  out.write(bytes);
  out.flush();
  out.close();
 }

 /**
  * 返回不帶擴展名的文件名
  *
  * @param fileName
  *            原始文件名
  * @return 不帶擴展名的文件名
  */
 public static String getFileNameWithoutExt(String fileName) {
  String shortFileName = fileName;
  if (fileName.indexOf('.') > -1) {
   shortFileName = fileName.substring(0, fileName.lastIndexOf('.'));
  }
  return shortFileName;
 }

 /**
  * 返回文件擴展名,帶「.」
  *
  * @param fileName
  *            原始文件名
  * @return 文件擴展名
  */
 public static String getFileNameExt(String fileName) {
  String fileExt = "";
  if (fileName.indexOf('.') > -1) {
   fileExt = fileName.substring(fileName.lastIndexOf('.'));
  }
  return fileExt;
 }

 /**
  * 獲得惟一文件
  *
  * @param fileName
  *            原始文件名
  * @return
  */
 public synchronized static File getUniqueFile(File repository,
   String fileName) {
  String shortFileName = getShortFileName(fileName);
  String tempFileName = getFileNameWithoutExt(shortFileName);
  File file = new File(repository, shortFileName);
  String fileExt = getFileNameExt(shortFileName);
  while (file.exists()) {
   file = new File(repository, tempFileName + "-"
     + Math.abs(new Random().nextInt()) + fileExt);
  }
  return file;
 }

 /**
  * 刪除文件方法,若是刪除不掉,將該文件加入刪除池,下次進行調用時將嘗試刪除池中的文件
  *
  * @param fileName
  *            fileName
  */
 public static void deleteFile(String fileName) {
  File file = new File(fileName);
  if (file.exists()) {
   deleteFile(file);
  }
 }

 /**
  * 刪除文件方法,若是刪除不掉,將該文件加入刪除池,下次進行調用時將嘗試刪除池中的文件
  *
  * @param file
  *            file
  */
 public static void deleteFile(File file) {
  file.delete();// 嘗試刪除文件
  if (file.exists()) {
   deleteFilesPool.add(file);
  }
  checkDeletePool();
 }

 /**
  * 檢查池,刪除池中文件,若是刪除成功則同時從池中移除。
  */
 private static void checkDeletePool() {
  File file;
  for (int i = deleteFilesPool.size() - 1; i >= 0; i--) {
   file = (File) deleteFilesPool.get(i);
   file.delete();
   if (file.exists() == false) {
    deleteFilesPool.remove(i);
   }
  }
  try {
   ObjectOutputStream out = new ObjectOutputStream(
     new FileOutputStream(POOL_FILE));
   out.writeObject(deleteFilesPool);
   out.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * 獲得惟一文件。一個類處在某個位置的class或jar包中,根據此位置獲得此類對應的文件。<br>
  * 不一樣位置的類獲得的文件是不同的。
  *
  * @param cl
  *            類
  * @param extension
  *            帶點的文件擴展名
  * @return
  */
 public static File getUniqueFile(Class cl, String extension) {
  int key = 0;
  // "cl.getResource"取得類的classpath
  URL url = cl.getResource(getClassNameWithoutPackage(cl) + ".class");
  if (url != null) {
   key = url.getPath().hashCode();
  }
  /**
   * 生成新文件,「System.getProperty("java.io.tmpdir")」爲路徑
   * 「getClassNameWithoutPackage(cl) + key + extension」爲文件名
   */
  File propFile = new File(System.getProperty("java.io.tmpdir"),
    getClassNameWithoutPackage(cl) + key + extension);
  return propFile;
 }

 private static String getClassNameWithoutPackage(Class cl) {
  String className = cl.getName();
  int pos = className.lastIndexOf('.') + 1;
  if (pos == -1)
   pos = 0;
  String name = className.substring(pos);
  return name;
 }

 /**
  * 獲得Java類所在的實際位置。一個類處在某個位置的class或jar包中,根據此位置獲得此類對應的文件。<br>
  * 不一樣位置的類獲得的文件是不同的。
  *
  * @param cl
  *            類
  * @return 類在系統中的實際文件名
  */
 public static String getRealPathName(Class cl) {

  URL url = cl.getResource(getClassNameWithoutPackage(cl) + ".class");
  if (url != null) {
   return url.getPath();
  }
  return null;
 }

}

相關文章
相關標籤/搜索