FileDocCategorySizeDatePackage
FileUtils.javaAPI DocGlassfish v2 API22034Fri May 04 22:34:50 BST 2007com.sun.enterprise.diagnostics.util

FileUtils

public class FileUtils extends Object
Collection of helper methods to manipulate files.

Fields Summary
static final int
BUFFER
private static Logger
logger
Constructors Summary
Methods Summary
public static voidcopyDir(java.lang.String srcDir, java.lang.String dstDir)
Copy files from the specified source directory to destination directory

param
srcDir Absolute path of the source directory to be copied
param
dstDir Absolute path of the destination directory and dstDir should exist

        copyDir(srcDir, dstDir, null, false);
    
public static voidcopyDir(java.lang.String srcDir, java.lang.String dstDir, boolean subDir)
Copy files from the specified source directory to destination directory

param
srcDir Absolute path of the source directory to be copied
param
dstDir Absolute path of the destination directory and dstDir should exist
param
subDir Boolean value specifies whether to copy files from subdirectory

        copyDir(srcDir, dstDir, null, subDir);
    
public static voidcopyDir(java.lang.String srcDir, java.lang.String dstDir, java.io.FilenameFilter filter, boolean subDir)
Copy files from the specified source directory to destination directory

param
srcDir Absolute path of the source directory to be copied
param
dstDir Absolute path of the destination directory and dstDir should exist
param
subDir Boolean value specifies whether to copy files from subdirectory

        int numFiles = 0;
        String [] strFiles = null;
        
        if (filter == null)
            strFiles = (new File(srcDir)).list();
        else
            strFiles = (new File(srcDir)).list(filter);
        
        if (strFiles != null)
            numFiles = strFiles.length;
        
        for (int i=0; i<numFiles; i++) {
            String srcFile = srcDir+File.separator+strFiles[i];
            String dstFile = dstDir+File.separator+strFiles[i];
            if ((new File(srcFile)).isFile()) {
                copyFile(srcFile,dstFile);
            } else if(subDir) {
                File dstSubDir = new File(dstFile);
                dstSubDir.mkdirs();
                copyDir(srcFile,dstFile,filter,subDir);
            }
        }
    
public static voidcopyFile(java.lang.String srcFile, java.lang.String destFile)
Copy source file to destination file.

param
srcFile Absolute path of the source file to be copied
param
destFile Absolute path of the destination file


                                  
          
      
        FileInputStream istream = new FileInputStream(srcFile);
        File dest = new File(destFile);
        copyFile(istream, dest);
    
public static voidcopyFile(java.io.InputStream istream, java.lang.String destFile)
Copy contents of the specified InputStream to destination file.

param
istream InputStream from which to read the source file
param
destFile Absolute path of the destination file

        File dest = new File(destFile);
        copyFile(istream, dest);
    
public static voidcopyFile(java.io.FileInputStream istream, java.lang.String destFile)
Copy contents of the specified InputStream to destination file.

param
istream FileInputStream from which to read the source file
param
destFile Absolute path of the destination file

        File dest = new File(destFile);
        copyFile(istream, dest);
    
public static voidcopyFile(java.io.InputStream istream, java.io.File dest)
Copy contents of the specified InputStream to desintation file.

param
istream InputStream from which to read the source file
param
dest Destination File to copy the source file to

        OutputStream ostream = new FileOutputStream(dest);
        dest.createNewFile();
        copyFileToStream(istream, ostream);
        ostream.close();
    
public static voidcopyFile(java.io.FileInputStream istream, java.io.File dest)
Copy contents of the specified InputStream to desintation file.

param
istream FileInputStream from which to read the source file
param
dest Destination File to copy the source file to

        if (!dest.exists())  {
            dest.getParentFile().mkdirs();
        }
        FileOutputStream ostream = new FileOutputStream(dest);
        dest.createNewFile();
        copyFileToStream(istream, ostream);
        ostream.close();
    
public static voidcopyFileToStream(java.io.InputStream istream, java.io.OutputStream ostream)
Copy file from an inputstream to a outputstream

param
istream Source input stream
param
ostream Destination output stream

        while(true){
            int nextByte = istream.read();
            if (nextByte==-1)
                break;
            ostream.write(nextByte);
        }
        istream.close();
    
public static voidcopyFileToStream(java.io.FileInputStream istream, java.io.FileOutputStream ostream)
Copy file from an file inputstream to a file outputstream

param
istream Source input stream
param
ostream Destination output stream

        FileChannel srcChannel = istream.getChannel();
        FileChannel destChannel = ostream.getChannel();
        srcChannel.transferTo(0, srcChannel.size(), destChannel);
        srcChannel.close();
        destChannel.close();
        istream.close();
    
public static voidcopyFileToWriter(java.io.InputStream istream, java.io.Writer writer)
Copy file from the specified inputstream to the specified Writer

param
istream Source input stream
param
writer Writer to which the file will be written

        while(true){
            int nextByte = istream.read();
            if (nextByte==-1)
                break;
            writer.write(nextByte);
        }
        istream.close();
    
public static voidcopySearchPatternToFile(java.lang.String srcFileName, java.lang.String dstFileName, java.lang.String searchPattern)
Copy lines containing search pattern from source file to destination file

param
srcFileName Source filename
param
dstFileName Destination filename
param
searchPattern Search pattern

        BufferedReader inFile = new BufferedReader(new FileReader(srcFileName));
        PrintWriter out = new PrintWriter
                (new BufferedWriter(new FileWriter(dstFileName)));
        String fileLine;
        while((fileLine = inFile.readLine()) != null)
            if (fileLine.matches("(?i).*"+searchPattern+".*"))
                out.println(fileLine);
        if (inFile != null)
            inFile.close();
        if (out != null)
            out.close();
    
public static voiddeleteFile(java.lang.String fileName)

        deleteFile(new File(fileName));
    
public static voiddeleteFile(java.io.File file)

        if (file != null) {
            if(file.isDirectory()){
                File[] files = file.listFiles();
                int size = files.length;
                for(int i =0; i < size; i++){
                    deleteFile(files[i]);
                }
            }
            file.delete();
        }
    
public static voidextractJarFiles(java.lang.String dir, java.lang.String dest)
Extracts the jar files in the given directory.
Note: will not look recursively (in subdirs) for .jar files.

param
dir Directory where .jar files has to be searched.
param
dest Destination directory where files will be extracted.

       try{
           File aJarDir = new File(dir);
           File files[] = aJarDir.listFiles();

           FilenameFilter filter = getFilenameFilter(".jar");

           for(File file : files)
           {
               //if(file.getName().toLowerCase().endsWith(".jar")){
               if(filter.accept(aJarDir, file.getName())){
                   String fileName = file.getName();
                   //String dirName = fileName.substring(0, fileName.toLowerCase().indexOf(".jar"));
                   //File outputDir = new File(dest+ File.separator + dirName);
                   File outputDir = new File(dest);

                   outputDir.mkdirs();


                   unjar(file,"",outputDir.getAbsolutePath());

                    file.delete();
               }
           }
       }
       catch(Exception e){
            logger.log(Level.WARNING, e.getMessage(), e.fillInStackTrace());
       }
   
public static java.util.ListgetFileListing(java.io.File aStartingDir, boolean recurse)
Recursively walk a directory tree and return a List of all Files found; the List is sorted using File.compareTo.

param
aStartingDir is a valid directory, which can be read.

        validateDirectory(aStartingDir);
        File[] filesAndDirs = aStartingDir.listFiles();
        List filesDirs = Arrays.asList(filesAndDirs);
        
        if (!recurse) {
            Collections.sort(filesDirs);
            return filesDirs;
        }
        
        Iterator filesIter = filesDirs.iterator();
        List result = new ArrayList();
        File file = null;
        while ( filesIter.hasNext() ) {
            file = (File)filesIter.next();
            result.add(file); //always add, even if directory
            if (recurse && !file.isFile()) {
                //must be a directory
                //recursive call!
                List deeperList = getFileListing(file, true);
                result.addAll(deeperList);
            }
            
        }
        Collections.sort(result);
        return result;
    
public static java.util.ListgetFileListing(java.io.File aStartingDir, boolean recurse, java.io.FilenameFilter nameFilter, java.util.Comparator comparator)
Recursively walk a directory tree and return a List of all Files matching the name pattern; the List is sorted using File.compareTo.

param
aStartingDir is a valid directory, which can be read.
boolean
recurse
param
nameFilter pattern for name
param
comparator sorts files

        
        validateDirectory(aStartingDir);
        
        File[] filesAndDirs = aStartingDir.listFiles(nameFilter);
        List filesDirs = Arrays.asList(filesAndDirs);
        
        if (!recurse) {
            Collections.sort(filesDirs, comparator);
            return filesDirs;
        }
        
        Iterator filesIter = filesDirs.iterator();
        List result = new ArrayList();
        File file = null;
        while ( filesIter.hasNext() ) {
            file = (File)filesIter.next();
            result.add(file); //always add, even if directory
            if (recurse && !file.isFile()) {
                //must be a directory
                //recursive call!
                List deeperList = getFileListing(file,true);
                result.addAll(deeperList);
            }
            
        }
        Collections.sort(result, comparator);
        return result;
    
public static java.lang.StringgetFileName(java.lang.String absPath)
Get the name of the file or directory from an absolute path

param
absPath Absolute path
return
Name of the directory or file

        File file = new File(absPath);
        return file.getName();
    
public static java.io.FilenameFiltergetFilenameFilter(java.lang.String extension)

        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                boolean result = false;
                if(name !=null && extension !=null){
                    result = name.toLowerCase().endsWith(extension.toLowerCase());
                }
                return result;
            }
        };
        return filter;
    
public static voidjarDirectory(java.io.File jarFile, java.lang.String dir)
Jar the contents of the specified directory including all subdirectories.

param
jarFile Ouput JAR file
param
dir Absoilute path of the directory to be JAR'd


        try{
            

            BufferedInputStream origin = null;
            File aJarDir = new File(dir);
            File parent = jarFile.getParentFile();
            
            if(!parent.exists())
                parent.mkdirs();
            
            FileOutputStream dest = new FileOutputStream(jarFile);
            JarOutputStream out = new JarOutputStream(new BufferedOutputStream(dest));
            out.setMethod(JarOutputStream.DEFLATED);
            byte data[] = new byte[BUFFER];
            
            List files = FileUtils.getFileListing( aJarDir, true );
            
            Iterator filesIter = files.iterator();
            int length = dir.length()  ;
            //System.out.println(" Directory : " + dir + " : Length : " + length);

            while( filesIter.hasNext() ){
                File f = (File)filesIter.next();
                String path = f.getPath();
                String relativePath = path.substring(length);
                if(relativePath.startsWith(""+File.separator))
                    relativePath = path.substring(length +1);
                    
                if (f.isDirectory())
                    relativePath = relativePath + "/";

                //System.out.println(" Relative Path :" +  relativePath);
                JarEntry entry = new JarEntry(relativePath);
                out.putNextEntry(entry);
                
                if (!f.isDirectory()){
                    FileInputStream fi = new FileInputStream(path);
                    origin = new BufferedInputStream(fi, BUFFER);
                    
                    int count;
                    while((count = origin.read(data, 0, BUFFER)) != -1) {
                        out.write(data, 0, count);
                    }
                }
                if(origin!=null)
                    try{origin.close();}catch(Exception e){e.printStackTrace();}
            }
            if(out!=null)
                try{out.close();}catch(Exception e){e.printStackTrace();}
        } catch (FileNotFoundException fnfEx){
            fnfEx.printStackTrace();
        } catch (IOException ioEx){
            ioEx.printStackTrace();
        }
    
public static voidmoveFile(java.lang.String sourceFile, java.lang.String destFile)

        copyFile(sourceFile, destFile);
        new File(sourceFile).delete();
    
public static voidunjar(java.io.File jarFile, java.lang.String entryPath, java.lang.String destDir)

        
        final int BUFFER = 2048;
        try {
            BufferedOutputStream dest;
            BufferedInputStream is;
            byte data[] = new byte[BUFFER];
            
            if (entryPath==null)
                entryPath="";
            
            JarFile jarfile = new JarFile(jarFile);
            Enumeration e = jarfile.entries();
            
            while(e.hasMoreElements()) { //going through each entries one by one
                JarEntry entry = (JarEntry) e.nextElement();
                is = new BufferedInputStream(jarfile.getInputStream(entry));
                
                String path = entry.getName();
                if (path.startsWith(entryPath)) {
                    int start = path.lastIndexOf("/");
                    String basis = null;
                    if(start != -1) {
                        basis = path.substring(0, start);
                    }
                    String filename = path.substring(start + 1);
                    File tmpPath = new File(destDir);
                    if(basis != null && basis.length() != 0){
                        tmpPath = new File(tmpPath, basis);
                        tmpPath.mkdirs();
                    }
                    
                    if(filename != null && filename.length() != 0){
                        File destfile = new File(tmpPath, filename);
                        FileOutputStream fos = new FileOutputStream(destfile);
                        dest = new BufferedOutputStream(fos, BUFFER);
                        
                        int count;
                        while ((count = is.read(data, 0, BUFFER))!= -1) {
                            dest.write(data, 0, count);
                        }
                        dest.flush();
                        dest.close();
                        is.close();
                    }
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    
private static voidvalidateDirectory(java.io.File aDirectory)
Directory is valid if it exists, does not represent a file, and can be read.

        if (aDirectory == null) {
            throw new IllegalArgumentException("Directory should not be null.");
        }
        if (!aDirectory.exists()) {
            throw new FileNotFoundException("Directory does not exist: " + aDirectory);
        }
        if (!aDirectory.isDirectory()) {
            throw new IllegalArgumentException("Is not a directory: " + aDirectory);
        }
        if (!aDirectory.canRead()) {
            throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
        }
    
public static voidzipDirectory(java.io.File jarFile, java.lang.String dir)
Jar the contents of the specified directory including all subdirectories.

param
jarFile Ouput JAR file
param
dir Absoilute path of the directory to be JAR'd

        try{
            BufferedInputStream origin = null;
            File aJarDir = new File(dir);
            FileOutputStream dest = new FileOutputStream(jarFile);
            ZipOutputStream out = new ZipOutputStream(
                    new BufferedOutputStream(dest));
            out.setMethod(ZipOutputStream.DEFLATED);
            byte data[] = new byte[BUFFER];
            
            List files = FileUtils.getFileListing( aJarDir, true );
            
            Iterator filesIter = files.iterator();
            while( filesIter.hasNext() ){
                File f = (File)filesIter.next();
                String path = f.getPath();
                if (f.isDirectory())
                    path = path + "/";
                
                ZipEntry entry = new ZipEntry(path);
                out.putNextEntry(entry);
                
                if (!f.isDirectory()){
                    FileInputStream fi = new FileInputStream(path);
                    origin = new BufferedInputStream(fi, BUFFER);
                    
                    int count;
                    while((count = origin.read(data, 0, BUFFER)) != -1) {
                        out.write(data, 0, count);
                    }
                }
                if(origin!=null)
                    try{origin.close();}catch(Exception e){e.printStackTrace();}
            }
            if(out!=null)
                try{out.close();}catch(Exception e){e.printStackTrace();}
        } catch (FileNotFoundException fnfEx){
            fnfEx.printStackTrace();
        } catch (IOException ioEx){
            ioEx.printStackTrace();
        }