FileUtil.java :  » ESB » cbesb-1.2 » com » bostechcorp » cbesb » common » util » Java Open Source

Java Open Source » ESB » cbesb 1.2 
cbesb 1.2 » com » bostechcorp » cbesb » common » util » FileUtil.java
/*
 * ChainBuilder ESB
 *          Visual Enterprise Integration
 * 
 * Copyright (C) 2006 Bostech Corporation
 * 
 * This program is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the 
 * Free Software Foundation; either version 2 of the License, or (at your option) 
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along with 
 * this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *
 * $Id: FileUtil.java 11975 2008-02-16 06:33:03Z shou $
 */
package com.bostechcorp.cbesb.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.Path;

/**
 * File utilities
 * 
 * @version $Revision: 383937 $
 */
public class FileUtil {

  /**
   * Buffer size used when copying the content of an input stream to an output
   * stream.
   */
  private static final int DEFAULT_BUFFER_SIZE = 1024 * 1024;

  protected static transient Log logger = LogFactory.getLog(FileUtil.class);

  public static File[] listFilesAsArray(File directory, FileFilter filter,
      boolean recurse) {
    Collection<File> files = listFiles(directory, filter, recurse);
    // Java4: Collection files = listFiles(directory, filter, recurse);

    File[] arr = new File[files.size()];
    return files.toArray(arr);
  }

  public static Collection<File> listFiles(
  // Java4: public static Collection listFiles(
      File directory, FileFilter filter, boolean recurse) {
    // List of files / directories
    Vector<File> files = new Vector<File>();
    // Java4: Vector files = new Vector();

    // Get files / directories in the directory
    File[] entries = directory.listFiles();

    // Go over entries
    for (File entry : entries) {
      // Java4: for (int f = 0; f < files.length; f++) {
      // Java4: File entry = (File) files[f];

      // If there is no filter or the filter accepts the
      // file / directory, add it to the list
      if (filter == null || filter.accept(entry)) {
        files.add(entry);
      }

      // If the file is a directory and the recurse flag
      // is set, recurse into the directory
      if (recurse && entry.isDirectory()) {
        files.addAll(listFiles(entry, filter, recurse));
      }
    }

    // Return collection of files
    return files;
  }

  /**
   * 
   * @param inputStream -
   *            to read from.
   * @return the string that was read.
   * @throws IOException
   */
  public static String readString(InputStream inputStream) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(
        inputStream, "utf-8"));
    String s = null;
    StringBuffer buffer = new StringBuffer();
    try {
      while ((s = in.readLine()) != null) {
        buffer.append(s).append("\n");
      }
    } catch (IOException e) {
      logger.error("Exception in readString(): " + e.getMessage());
      if (logger.isDebugEnabled()) {
        logger.debug("Exception in readString():", e);
      }
    }
    return buffer.toString();
  }

  /**
   * 
   * @param inputStream -
   *            to read from.
   * @return the bytes that were read.
   * @throws IOException
   */
  public static byte[] readBytes(InputStream inputStream) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedInputStream bis = new BufferedInputStream(inputStream);
    int b = bis.read();
    while (b != -1) {
      baos.write(b);
      b = bis.read();
    }
    return baos.toByteArray();
  }

  /**
   * 
   * @param filename -
   *            filename to read.
   * @return - the string that was read.
   * @throws IOException
   */
  public static String readStringFromFile(String filename) throws IOException {
    return readString(new FileInputStream(filename));
  }

  /**
   * 
   * @param filename -
   *            filename to read.
   * @return - the bytes that were read.
   * @throws IOException
   */
  public static byte[] readBytesFromFile(String filename) throws IOException {
    return readBytes(new FileInputStream(filename));
  }

  /**
   * 
   * @param fileInClassPath
   *            the filename in class path.
   * @return the string that was read from file.
   * @throws IOException
   */
  public static String readString(String fileInClassPath) throws IOException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    return readString(cl.getResourceAsStream(fileInClassPath));
  }

  /**
   * 
   * @param fileInClassPath
   *            the filename in class path.
   * @return the bytes that were read from file.
   * @throws IOException
   */
  public static byte[] readBytes(String fileInClassPath) throws IOException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    return readBytes(cl.getResourceAsStream(fileInClassPath));
  }

  public static File getFileFromClassPath(String name)
      throws URISyntaxException {
    URL url = Thread.currentThread().getContextClassLoader().getResource(
        "xslident.xsl");
    File file = new File(new URI(url.toString()));
    return file;
  }

  /**
   * Fast & simple file copy. 
   * @param source
   * @param dest
   * @throws IOException
   */
  public static void copy(File source, File dest) throws IOException {
    FileChannel in = null, out = null;
    try {
      in = new FileInputStream(source).getChannel();
      out = new FileOutputStream(dest).getChannel();
      long size = in.size();
      MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0,
          size);
      out.write(buf);
    } finally {
      if (in != null)
        in.close();
      if (out != null)
        out.close();
    }
  }

  /**
   * Simple Copy "from" to "to"
   * @param from
   * @param to
   * @return
   * Note: use fast copy from V1.2
   */
  public static boolean copyFile(String from, String to) {
    try {
      copy(new File(from), new File(to));
    } catch (Exception e) {
      ErrorUtil.printError("Exception in copyFile(): ", e);
      return false;
    }
    return true;
  }

  public static void copy(String from, String to) throws IOException {
    int buff_size = 100000;
    byte[] buffer = new byte[buff_size];
    InputStream in = null;
    OutputStream out = null;

    try {
      in = new FileInputStream(from);
      out = new FileOutputStream(to);

      while (true) {
        synchronized (buffer) {
          int amountread = in.read(buffer);

          if (amountread == -1) {
            break;
          }

          out.write(buffer, 0, amountread);
        }
      }
    } finally {
      if (in != null) {
        in.close();
      }

      if (out != null) {
        out.close();
      }
    }
  }

  //  public static boolean copyFile(String from, String to) {
  //    File fromFile, toFile;
  //    fromFile = new File(from);
  //    toFile = new File(to);
  //    FileInputStream fis = null;
  //    FileOutputStream fos = null;
  //    try {
  //      toFile.createNewFile();
  //      fis = new FileInputStream(fromFile);
  //      fos = new FileOutputStream(toFile);
  //      int bytesRead;
  //      byte[] buf = new byte[4 * 1024];// 4K buffer
  //      while ((bytesRead = fis.read(buf)) != -1) {
  //        fos.write(buf, 0, bytesRead);
  //      }
  //      fos.flush();
  //      fos.close();
  //      fis.close();
  //    } catch (IOException e) {
  //      ErrorUtil.printError("Exception in copyFile(): ", e);
  //      return false;
  //    }
  //    return true;
  //  }

  /**
   * Move a File
   * 
   * @param src
   * @param targetDirectory
   * @throws IOException
   */
  public static void moveFile(File src, File targetDirectory)
      throws IOException {
    if (!src.renameTo(new File(targetDirectory, src.getName()))) {
      throw new IOException("Failed to move " + src + " to "
          + targetDirectory);
    }
  }

  /**
   * Build a path- but do not create it
   * 
   * @param parent
   * @param subDirectory
   * @return a File representing the path
   */
  public static File getDirectoryPath(File parent, String subDirectory) {
    File result = null;
    if (parent != null) {
      result = new File(parent, subDirectory);
    }
    return result;
  }

  /**
   * Build a directory path - creating directories if neccesary
   * 
   * @param file
   * @return true if the directory exists, or making it was successful
   */
  public static boolean buildDirectory(File file) {
    return file.exists() || file.mkdirs();
  }

  /**
   * Copy in stream to an out stream
   * 
   * @param in
   * @param out
   * @throws IOException
   */
  public static void copyInputStream(InputStream in, OutputStream out)
      throws IOException {
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int len;
    while ((len = in.read(buffer)) >= 0) {
      out.write(buffer, 0, len);
    }
    in.close();
    out.close();
  }

  /**
   * Unpack a zip file
   * 
   * @param theFile
   * @param targetDir
   * @return the file
   * @throws IOException
   */
  public static File unpackArchive(File theFile, File targetDir)
      throws IOException {
    if (!theFile.exists()) {
      throw new IOException(theFile.getAbsolutePath() + " does not exist");
    }
    if (!targetDir.exists()) {
      targetDir.mkdirs();
    }
    ZipFile zipFile;
    zipFile = new ZipFile(theFile);
    for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
      ZipEntry entry = (ZipEntry) entries.nextElement();
      File file = new File(targetDir, File.separator + entry.getName());
      // Take the sledgehammer approach to creating directories
      // to work around ZIP's that incorrectly miss directories
      file.mkdirs();
      if (!entry.isDirectory()) {
        file.delete();
        copyInputStream(zipFile.getInputStream(entry),
            new BufferedOutputStream(new FileOutputStream(file)));
      }
    }
    zipFile.close();
    return theFile;
  }

  /**
   * Unpack a zip file
   * 
   * @param theFile
   * @param targetDir
   * @return the file
   * @throws IOException
   */
  public static File unpackArchiveCheckOverwrite(File theFile, File targetDir)
      throws IOException {
    if (!theFile.exists()) {
      throw new IOException(theFile.getAbsolutePath() + " does not exist");
    }
    if (!targetDir.exists()) {
      targetDir.mkdirs();
    }
    ZipFile zipFile;
    zipFile = new ZipFile(theFile);
    for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
      ZipEntry entry = (ZipEntry) entries.nextElement();
      File file = new File(targetDir, File.separator + entry.getName());
      // Take the sledgehammer approach to creating directories
      // to work around ZIP's that incorrectly miss directories
      if (file.lastModified() <= entry.getTime()) {
        file.mkdirs();
        if (!entry.isDirectory()) {
          file.delete();
          // if current file time > zip entry time then don't
          // owerwrite
          // entry.getTime();
          copyInputStream(
              zipFile.getInputStream(entry),
              new BufferedOutputStream(new FileOutputStream(file)));
        }
      }
    }
    zipFile.close();
    return theFile;
  }

  /**
   * Unpack an archive from a URL
   * 
   * @param url
   * @param targetDir
   * @return the file to the url
   * @throws IOException
   */
  public static File unpackArchive(URL url, File targetDir)
      throws IOException {
    if (!targetDir.exists()) {
      targetDir.mkdirs();
    }
    InputStream in = new BufferedInputStream(url.openStream(),
        DEFAULT_BUFFER_SIZE);
    // make sure we get the actual file
    File zip = File.createTempFile("arc", ".zip", targetDir);
    OutputStream out = new BufferedOutputStream(new FileOutputStream(zip));
    copyInputStream(in, out);
    out.close();
    return unpackArchive(zip, targetDir);
  }

  /**
   * Validate that an archive contains a named entry
   * 
   * @param theFile
   * @param name
   * @return true if the entry exists
   * @throws IOException
   */
  public static boolean archiveContainsEntry(File theFile, String name)
      throws IOException {
    boolean result = false;
    ZipFile zipFile;
    zipFile = new ZipFile(theFile);
    for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
      ZipEntry entry = (ZipEntry) entries.nextElement();
      if (entry.getName().equals(name)) {
        result = true;
        break;
      }
    }
    zipFile.close();
    return result;
  }

  /**
   * Create a unique directory within a directory 'root'
   * 
   * @param rootDir
   * @param seed
   * @return unique directory
   * @throws IOException
   */
  public synchronized static File createUniqueDirectory(File rootDir,
      String seed) throws IOException {
    int index = seed.lastIndexOf('.');
    if (index > 0) {
      seed = seed.substring(0, index);
    }
    File result = null;
    int count = 0;
    while (result == null) {
      String name = seed + "." + count + ".tmp";
      File file = new File(rootDir, name);
      if (!file.exists()) {
        file.mkdirs();
        result = file;
      }
      count++;
    }
    return result;
  }

  /**
   * Delete a file
   * 
   * @param fileToDelete
   * @return true if the File is deleted
   */
  public static boolean deleteFile(File fileToDelete) {
    boolean result = true;
    if (fileToDelete != null && fileToDelete.exists()) {
      if (fileToDelete.isDirectory()) {
        File[] files = fileToDelete.listFiles();
        if (files == null) {
          result = false;
        } else {
          for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (!file.getName().equals(".")
                && !file.getName().equals("..")) {
              if (file.isDirectory()) {
                result &= deleteFile(file);
              } else {
                result &= file.delete();
              }
            }
          }
        }
      }
      result &= fileToDelete.delete();
    }
    return result;
  }

  /**
   * Zip up a directory
   * 
   * @param directory
   * @param zipName
   * @throws IOException
   */
  public static void zipDir(String directory, String zipName)
      throws IOException {
    // create a ZipOutputStream to zip the data to
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipName));
    String path = "";
    zipDir(directory, zos, path);
    // close the stream
    zos.close();
  }

  /**
   * Zip up a directory path
   * 
   * @param directory
   * @param zos
   * @param path
   * @throws IOException
   */
  public static void zipDir(String directory, ZipOutputStream zos, String path)
      throws IOException {
    File zipDir = new File(directory);
    // get a listing of the directory content
    String[] dirList = zipDir.list();
    byte[] readBuffer = new byte[2156];
    int bytesIn = 0;
    // loop through dirList, and zip the files
    for (int i = 0; i < dirList.length; i++) {
      File f = new File(zipDir, dirList[i]);
      if (f.isDirectory()) {
        String filePath = f.getPath();
        zipDir(filePath, zos, path + f.getName() + "/");
        continue;
      }
      FileInputStream fis = new FileInputStream(f);
      ZipEntry anEntry = new ZipEntry(path + f.getName());
      zos.putNextEntry(anEntry);
      while ((bytesIn = fis.read(readBuffer)) != -1) {
        zos.write(readBuffer, 0, bytesIn);
      }
      fis.close();
    }
  }

  public static InputStream String2InputStream(String str) {
    ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
    return stream;
  }

  //  /**
  //   * 
  //   * @param oldFile
  //   * @param newPath
  //   */
  //  @Deprecated
  //  // TODO: throw all the exceptions
  //  public static void copyFile(File oldFile, String newPath) {
  //    try {
  //      int byteRead = 0;
  //      int byteSum = 0;
  //      if (oldFile.exists()) {
  //        InputStream inputStream = new FileInputStream(oldFile);
  //        File newFolder = new File(newPath);
  //        if (!newFolder.exists() || !newFolder.isDirectory()) {
  //          newFolder.mkdirs();
  //        }
  //        String newFilename = newPath + File.separator
  //            + oldFile.getName();
  //        OutputStream outputStream = new FileOutputStream(newFilename);
  //        byte[] buffer = new byte[1024];
  //        while ((byteRead = inputStream.read(buffer)) != -1) {
  //          byteSum += byteRead;
  //          outputStream.write(buffer, 0, byteRead);
  //        }
  //        outputStream.close();
  //        inputStream.close();
  //      }
  //    } catch (Exception e) {
  //      e.printStackTrace();
  //    }
  //  }

  /**
   * Copy source(old) file to it's new location - newPath
   * Note: adapted to use fast Copy
   * @param oldFile
   * @param newPath
   * 
   * Note: use fast copy from V1.2
   */
  public static void copyFile(File oldFile, String newPath) {
    try {
      if (oldFile.exists()) {
        File newFolder = new File(newPath);
        if (oldFile.getParent().equals(newPath))
          return;
        if (!newFolder.exists() || !newFolder.isDirectory()) {
          newFolder.mkdir();
        }
        String newFilename = newPath + File.separator
            + oldFile.getName();
        copy(oldFile, new File(newFilename));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Copy File Resource from source to destination. If the File resource is a
   * folder then it's content will be copyed recursively Note: Adapted to use
   * Fast Copy
   * 
   * @param sourceStringPath
   * @param destinationStringPath
   * @param filter -
   *            just in case you don't need all files
   * @throws FileNotFoundException
   * @throws IOException
   */
  public static void copyFilesRecursively(String sourceStringPath,
      String destinationStringPath, FileFilter filter)
      throws FileNotFoundException, IOException {
    File src = new File(sourceStringPath);
    File dest = new File(destinationStringPath);
    //  System.out.println("From:"+sourceStringPath+" \n To:"+destinationStringPath);
    if (!src.exists())
      throw new FileNotFoundException("Directory " + sourceStringPath
          + " does not exist!");

    if (dest.exists()) // if destination exist then check more
      if (dest.isDirectory() != src.isDirectory()) {
        if (!src.isDirectory()) {
          // change destination, ie append file name
          dest = new File(dest.getAbsolutePath() + File.separator
              + src.getName());
        } else {
          throw new IOException("Source(" + src.getAbsolutePath()
              + ") \n is a Directory and Destination("
              + dest.getAbsolutePath() + ")\n is a File, "
              + "Cannot copy directory to a file");
        }
      }

    if (src.isDirectory()) {
      if (!buildDirectory(dest))
        throw new IOException(destinationStringPath
            + " could not be created.");
      String list[] = src.list(null);
      for (int i = 0; i < list.length; i++) {
        String dest1 = dest.getAbsolutePath() + File.separator
            + list[i];
        String src1 = src.getAbsolutePath() + File.separator + list[i];
        copyFilesRecursively(src1, dest1, filter);
      }
    } else {
      copy(src, dest);/* Fast copy */
    }
  }

  public static void copyFiles(HashMap<String, String> map)
      throws IOException {
    for (String source : map.keySet()) {
      File src = new File(source);
      File dest = new File(map.get(source));
      FileUtil.buildDirectory(new Path(map.get(source))
          .removeLastSegments(1).toFile());
      copy(src, dest);
    }
  }

  /**
   * return Absolut URI, so the file can be accesed
   * 
   * @param WsdlLocation
   * @param relativeLocationURI
   * @return
   */
  public static String processLocationURI(String wsdlFixedURI,
      String relativeLocationURI) {
    String pathToFile = "";
    URI uri = URI.create(wsdlFixedURI);
    pathToFile += uri.resolve(relativeLocationURI);
    return pathToFile;
  }

  //  public static void main(String[] args) {
  //    try {
  //      copyFilesRecursively("c:\\asd", "c:\\AUTOEXEC.BAT", null);
  //    } catch (FileNotFoundException e) {
  //      // TODO Auto-generated catch block
  //      e.printStackTrace();
  //    } catch (IOException e) {
  //      // TODO Auto-generated catch block
  //      e.printStackTrace();
  //    }
  //  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.