fileutil.java

来自「jakarta-taglibs」· Java 代码 · 共 357 行

JAVA
357
字号
/*
 * Copyright 1999,2004 The Apache Software Foundation.
 * 
 * Licensed 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.
 */

//This handy class ripped from Avalaon util.io package.
//package org.apache.avalon.util.io;
package org.apache.taglibs.gnat.util;

import java.io.*;
import java.net.URL;

/**
 * This class provides basic facilities for manipulating files.
 *
 * @author <a href="mailto:donaldp@apache.org">Peter Donald</a>
 */
public final class FileUtil
{
    /**
     * Private constructor to prevent instantiation.
     *
     */
    private FileUtil()
    {
    }

    public static String removeExtention( final String filename )
    {
        final int index = filename.lastIndexOf( '.' );
        
        if( -1 == index ) 
        {
            return filename;
        }
        else
        {
            return filename.substring( 0, index );
        }
    }

    public static String removePath( final String filepath )
    {
        final int index = filepath.lastIndexOf( File.separator );

        if( -1 == index ) 
        {
            return filepath;
        }
        else
        {
            return filepath.substring( index + 1 );
        }
    }

    /**
     * Copy file from source to destination.
     */
    public static void copyFileToDirectory( final String source, 
                                            final String destinationDirectory ) 
        throws IOException 
    {
        copyFileToDirectory( new File( source ), new File( destinationDirectory ) );
    }

    /**
     * Copy file from source to destination.
     */
    public static void copyFileToDirectory( final File source, 
                                            final File destinationDirectory ) 
        throws IOException 
    {
        if( destinationDirectory.exists() && !destinationDirectory.isDirectory() )
        {
            throw new IllegalArgumentException( "Destination is not a directory" );
        }

        copyFile( source, new File( destinationDirectory, source.getName() ) );
    }

    /**
     * Copy file from source to destination.
     */
    public static void copyFile( final File source, final File destination ) 
        throws IOException 
    {
        //check source exists
        if( !source.exists() )
        {
            throw new IOException( "File " + source + " does not exist" );
        }

        //does destinations directory exist ?
        if( !destination.getParentFile().exists() )
        {
            destination.mkdirs();
        }

        //make sure we can write to destination
        if( destination.exists() && !destination.canWrite() )
        {
            throw new IOException( "Unable to open file " + destination + " for writing." );
        }

        copy( new FileInputStream( source ), new FileOutputStream( destination ) );

        if( source.length() != destination.length() )
        {
            throw new IOException( "Failed to copy full contents from " + source + 
                                   " to " + destination );
        }
    } 

    public static void copyURLToFile( final URL source, final File destination ) 
        throws IOException 
    {
        //does destinations directory exist ?
        if( !destination.getParentFile().exists() )
        {
            destination.mkdirs();
        }
        
        //make sure we can write to destination
        if( destination.exists() && !destination.canWrite() )
        {
            throw new IOException( "Unable to open file " + destination + " for writing." );
        }
        
        copy( source.openStream(), new FileOutputStream( destination ) );
    } 

    /**
     * Copy stream-data from source to destination.
     */
    public static void copy( final InputStream source, final OutputStream destination ) 
        throws IOException 
    {
        try
        {
            final BufferedInputStream input = new BufferedInputStream( source );
            final BufferedOutputStream output = new BufferedOutputStream( destination );
            
            final int BUFFER_SIZE = 1024 * 4;
            final byte[] buffer = new byte[ BUFFER_SIZE ];
            
            while( true )
            {
                final int count = input.read( buffer, 0, BUFFER_SIZE );
                if( -1 == count ) break;
                
                // write out those same bytes
                output.write( buffer, 0, count );
            }
            
            //needed to flush cache
            input.close();
            output.close();
        }
        finally
        {
            try { source.close(); } catch( final IOException ioe ) {}
            try { destination.close(); } catch( final IOException ioe ) {}
        }
    } 

    /** Will concatenate 2 paths, dealing with ..
     * ( /a/b/c + d = /a/b/d, /a/b/c + ../d = /a/d )
     * 
     * Thieved from Tomcat sources...
     * 
     * @return null if error occurs
     */
    public static String catPath( String lookupPath, String path )
    {
        // Cut off the last slash and everything beyond
        int index = lookupPath.lastIndexOf( "/" );
        lookupPath = lookupPath.substring( 0, index );
        
        // Deal with .. by chopping dirs off the lookup path
        while( path.startsWith( "../" ) ) 
        { 
            if( lookupPath.length() > 0 )
            {
                index = lookupPath.lastIndexOf( "/" );
                lookupPath = lookupPath.substring( 0, index );
            } 
            else
            {
                // More ..'s than dirs, return null
                return null;
            }
            
            index = path.indexOf( "../" ) + 3;
            path = path.substring( index );
        }
        
        return lookupPath + "/" + path;
    }

    public static File resolveFile( final File baseFile, String filename ) 
    {
        if( '/' != File.separatorChar ) 
        {
            filename = filename.replace( '/', File.separatorChar );
        }

        if( '\\' != File.separatorChar ) 
        {
            filename = filename.replace( '\\', File.separatorChar );
        }

        // deal with absolute files
        if( filename.startsWith( File.separator ) )
        {
            File file = new File( filename );

            try { file = file.getCanonicalFile(); } 
            catch( final IOException ioe ) {}

            return file;
        }

        final char[] chars = filename.toCharArray();
        final StringBuffer sb = new StringBuffer();

        //remove duplicate file seperators in succession - except 
        //on win32 as UNC filenames can be \\AComputer\AShare\myfile.txt
        int start = 0;
        if( '\\' == File.separatorChar ) 
        {
            sb.append( filename.charAt( 0 ) );
            start++;
        }

        for( int i = start; i < chars.length; i++ )
        {
            final boolean doubleSeparator = 
                File.separatorChar == chars[ i ] && File.separatorChar == chars[ i - 1 ];

            if( !doubleSeparator ) sb.append( chars[ i ] );
        }
        
        filename = sb.toString();

        //must be relative...
        File file = (new File( baseFile, filename )).getAbsoluteFile();

        try { file = file.getCanonicalFile(); }
        catch( final IOException ioe ) {}

        return file;
    }

    /**
     * Delete a file. If file is directory delete it and all sub-directories.
     */
    public static void forceDelete( final String file )
        throws IOException 
    {
        forceDelete( new File( file ) );
    }

    /**
     * Delete a file. If file is directory delete it and all sub-directories.
     */
    public static void forceDelete( final File file )
        throws IOException 
    {
        if( file.isDirectory() ) deleteDirectory( file );
        else
        {
            if( false == file.delete() )
            {
                throw new IOException( "File " + file + " unable to be deleted." );
            }
        }
    }

    /**
     * Recursively delete a directory.
     */
    public static void deleteDirectory( final String directory )
        throws IOException 
    {
        deleteDirectory( new File( directory ) );
    }

    /**
     * Recursively delete a directory.
     */
    public static void deleteDirectory( final File directory )
        throws IOException 
    {
        if( !directory.exists() ) return;

        cleanDirectory( directory );
        if( false == directory.delete() )
        {
            throw new IOException( "Directory " + directory + " unable to be deleted." );
        }
    }  

    /**
     * Clean a directory without deleting it.
     */
    public static void cleanDirectory( final String directory )
        throws IOException 
    {
        cleanDirectory( new File( directory ) );
    }
    
    /**
     * Clean a directory without deleting it.
     */
    public static void cleanDirectory( final File directory )
        throws IOException 
    {
        if( !directory.exists() ) 
        {
            throw new IllegalArgumentException( directory + " does not exist" );
        }
        
        if( !directory.isDirectory() )
        {
            throw new IllegalArgumentException( directory + " is not a directory" );
        }
        
        final File[] files = directory.listFiles();
        
        for( int i = 0; i < files.length; i++ ) 
        {
            final File file = files[ i ];
            
            if( file.isFile() ) file.delete();
            else if( file.isDirectory() ) 
            {
                cleanDirectory( file );
                if( false == file.delete() )
                {
                    throw new IOException( "Directory " + file + " unable to be deleted." );
                }
            }
        }
    } 
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?