net.sf.mmm.util.file.base
Class FileUtilImpl

java.lang.Object
  extended by net.sf.mmm.util.component.base.AbstractComponent
      extended by net.sf.mmm.util.component.base.AbstractLoggableComponent
          extended by net.sf.mmm.util.file.base.FileUtilImpl
All Implemented Interfaces:
FileUtil

@Singleton
@Named
public class FileUtilImpl
extends AbstractLoggableComponent
implements FileUtil

This class is a collection of utility functions for File handling and manipulation.

Since:
1.0.1
Author:
Joerg Hohwiller (hohwille at users.sourceforge.net)
See Also:
getInstance()

Nested Class Summary
protected static class FileUtilImpl.PathSegment
          This inner class represents a segment of a glob-matching path.
 
Field Summary
private static String HOME_ROOT
          The typical home directory of the user "root" under Unix/Linux.
private static FileUtil instance
           
private  StringUtil stringUtil
           
private  File temporaryDirectory
           
private  String temporaryDirectoryPath
           
private static String UNC_PATH_PREFIX
          The prefix of an UNC (Uniform Naming Convention) path (e.g.
private static Pattern URL_SCHEMA_PATTERN
          The Pattern for an URL schema such as http:// or ftp://.
private  File userHomeDirectory
           
private  String userHomeDirectoryPath
           
private  String userLogin
           
 
Fields inherited from interface net.sf.mmm.util.file.api.FileUtil
NO_FILES, PATH_SEGMENT_CURRENT, PATH_SEGMENT_PARENT, PROPERTY_TMP_DIR, PROPERTY_USER_HOME
 
Constructor Summary
FileUtilImpl()
          The constructor.
 
Method Summary
private  void collectMatchingFiles(File cwd, FileUtilImpl.PathSegment[] segments, int segmentIndex, FileType fileType, List<File> list)
          This method adds all files matching to the given path and fileType to the list.
 boolean collectMatchingFiles(File cwd, String path, FileType fileType, List<File> list)
          This method adds all files matching the given path and fileType to the list.
 void copyFile(File source, File destination)
          This method copies the file given by source to the file given by destination.
 void copyFile(File source, File destination, boolean keepFlags)
          This method copies the file given by source to the file given by destination.
 void copyRecursive(File source, File destination, boolean allowOverwrite)
          This method copies the file or directory given by source into the given destination.
 void copyRecursive(File source, File destination, boolean allowOverwrite, FileFilter filter)
          This method copies the file or directory given by source into the given destination.
private  void copyRecursive(File source, File destination, FileFilter filter)
          This method copies the file or directory given by source into the given destination.
 int deleteChildren(File directory)
          This method deletes all children of the given directory recursively.
 int deleteRecursive(File path)
          This method deletes the given path.
protected  void doInitialize()
          This method performs the actual initialization.
 String getBasename(String filename)
          This method gets the basename of the given filename (path).
 String getDirname(String filename)
          This method gets the directory-name of the given filename (path).
 String getExtension(String filename)
          This method extracts the extension from the given filename.
static FileUtil getInstance()
          This method gets the singleton instance of this FileUtilImpl.
 File[] getMatchingFiles(File cwd, String path, FileType fileType)
          This method gets all files matching to the given path and fileType.
 FileAccessPermissions getPermissions(File file, FileAccessClass accessClass)
          This method gets the permissions of the given file.
protected  StringUtil getStringUtil()
          This method gets the StringUtilImpl that is used by this FileUtilImpl.
 File getTemporaryDirectory()
          This method gets the File representing the temporary directory.
 File getUserHomeDirectory()
          This method gets the File representing the home directory of the user.
 String getUserLogin()
          This method gets the String.
 String normalizePath(String path)
          This method is a shortcut for normalizePath(path, File.separatorChar).
 String normalizePath(String path, char separator)
          This method normalizes a given path.
private  String normalizePathInternal(String path, char slash)
          This method handles normalizePath(String) internally.
 void setPermissions(File file, FileAccessPermissions permissions)
          This method sets the permissions of the given file.
 void setStringUtil(StringUtil stringUtil)
          This method sets the StringUtil.
 void setTemporaryDirectoryPath(String tmpDir)
          This method sets the tmp directory.
 void setUserHomeDirectoryPath(String userHome)
          This method set the users home directory.
 void setUserLogin(String userLogin)
           
private  boolean tokenizePath(String path, List<FileUtilImpl.PathSegment> list, PatternCompiler patternCompiler)
          This method tokenized the given path by adding FileUtilImpl.PathSegments to the given list.
 
Methods inherited from class net.sf.mmm.util.component.base.AbstractLoggableComponent
getLogger, setLogger
 
Methods inherited from class net.sf.mmm.util.component.base.AbstractComponent
doInitialized, getInitializationState, initialize
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

HOME_ROOT

private static final String HOME_ROOT
The typical home directory of the user "root" under Unix/Linux.

See Also:
Constant Field Values

UNC_PATH_PREFIX

private static final String UNC_PATH_PREFIX
The prefix of an UNC (Uniform Naming Convention) path (e.g. \\10.0.0.1\share).

See Also:
Constant Field Values

URL_SCHEMA_PATTERN

private static final Pattern URL_SCHEMA_PATTERN
The Pattern for an URL schema such as http:// or ftp://.


instance

private static FileUtil instance
See Also:
getInstance()

stringUtil

private StringUtil stringUtil
See Also:
getStringUtil()

userHomeDirectoryPath

private String userHomeDirectoryPath
See Also:
setUserHomeDirectoryPath(String)

userHomeDirectory

private File userHomeDirectory
See Also:
getUserHomeDirectory()

userLogin

private String userLogin
See Also:
getUserLogin()

temporaryDirectoryPath

private String temporaryDirectoryPath
See Also:
setTemporaryDirectoryPath(String)

temporaryDirectory

private File temporaryDirectory
See Also:
getTemporaryDirectory()
Constructor Detail

FileUtilImpl

public FileUtilImpl()
The constructor.

Method Detail

getInstance

public static FileUtil getInstance()
This method gets the singleton instance of this FileUtilImpl.
This design is the best compromise between easy access (via this indirection you have direct, static access to all offered functionality) and IoC-style design which allows extension and customization.
For IoC usage, simply ignore all static getInstance() methods and construct new instances via the container-framework of your choice (like plexus, pico, springframework, etc.). To wire up the dependent components everything is properly annotated using common-annotations (JSR-250). If your container does NOT support this, you should consider using a better one.

Returns:
the singleton instance.

doInitialize

protected void doInitialize()
This method performs the actual initialization. It is called when AbstractComponent.initialize() is invoked for the first time.
ATTENTION:
When you override this method from a sub-class you need to do a super.AbstractComponent.doInitialize().

Overrides:
doInitialize in class AbstractLoggableComponent

getStringUtil

protected StringUtil getStringUtil()
This method gets the StringUtilImpl that is used by this FileUtilImpl.

Returns:
the stringUtil the StringUtilImpl.

setStringUtil

@Inject
public void setStringUtil(StringUtil stringUtil)
                   throws AlreadyInitializedException
This method sets the StringUtil. It can only be set once during initialization.

Parameters:
stringUtil - the stringUtil to set.
Throws:
AlreadyInitializedException - if the value has already been set.

getUserHomeDirectory

public File getUserHomeDirectory()
This method gets the File representing the home directory of the user.

Specified by:
getUserHomeDirectory in interface FileUtil
Returns:
the home directory of the user.

setUserHomeDirectoryPath

public void setUserHomeDirectoryPath(String userHome)
                              throws AlreadyInitializedException
This method set the users home directory. It can only be set once during initialization.

Parameters:
userHome - is the home directory of the user.
Throws:
AlreadyInitializedException - if the value has already been set.

getTemporaryDirectory

public File getTemporaryDirectory()
This method gets the File representing the temporary directory.

Specified by:
getTemporaryDirectory in interface FileUtil
Returns:
the tmp directory.

setTemporaryDirectoryPath

public void setTemporaryDirectoryPath(String tmpDir)
                               throws AlreadyInitializedException
This method sets the tmp directory.

Parameters:
tmpDir - the tmpDir to set
Throws:
AlreadyInitializedException - if the value has already been set.

getUserLogin

public String getUserLogin()
This method gets the String.

Returns:
the String.

setUserLogin

public void setUserLogin(String userLogin)
Parameters:
userLogin - is the userLogin to set

normalizePath

public String normalizePath(String path)
This method is a shortcut for normalizePath(path, File.separatorChar).

Specified by:
normalizePath in interface FileUtil
Parameters:
path - is the path to resolve.
Returns:
the resolved path.
See Also:
FileUtil.normalizePath(String, char)

normalizePath

public String normalizePath(String path,
                            char separator)
This method normalizes a given path. It will resolve ".." and "." segments, normalize backslashes and remove duplicated slashes. Further it can resolve "~" at the beginning of the path (like in bash-scripts, etc.). Therefore this method resolves the path in such situations (e.g. to "/home/login/foo") and returns a physical path.
Here are some examples assuming that separator is '/' (backslashes are NOT escaped):
path normalizePath(path)
"folder/subfolder//../.\some.file" "folder/some.file"
"../.\some.file" "../some.file"
"http://www.host.com/foo/bar/./test/.././.." "http://www.host.com/foo"
"\\unc.host\printers\pr3761" "\\unc.host\printers\pr3761"
"~/documents/index.html" FileUtil.getUserHomeDirectory() + "/documents/index.html"
"~root/subfolder/../folder/.//index.html" "/root/folder/index.html"
ATTENTION:
Normalizing home-directories of other users (e.g. "~user/") makes various assumptions and is NOT guaranteed to be correct in any case.

Specified by:
normalizePath in interface FileUtil
Parameters:
path - is the path to resolve.
separator - is the character to use as file separator.
Returns:
the resolved path.

normalizePathInternal

private String normalizePathInternal(String path,
                                     char slash)
This method handles normalizePath(String) internally.

Parameters:
path - is the path.
slash - is the character used to to separate folders.
Returns:
the resolved path.

getExtension

public String getExtension(String filename)
This method extracts the extension from the given filename.
Example: getExtension("test.java") would return "java".
ATTENTION:
If the filename is just a dot followed by the extension (e.g. ".java"), the empty string is returned.

Specified by:
getExtension in interface FileUtil
Parameters:
filename - is the filename and may include an absolute or relative path.
Returns:
the extension of the given filename excluding the dot in lowercase or the empty string if NOT present.

getBasename

public String getBasename(String filename)
This method gets the basename of the given filename (path). The basename is the raw name of the file without the path.
Examples:
filename getBasename(filename)
   
/ /
\/\ \
/. .
/foo.bar foo.bar
/foo/bar/ bar
c:\\  
c:\\foo foo
http://foo.org/bar bar

Specified by:
getBasename in interface FileUtil
Parameters:
filename - is the path to a file or directory.
Returns:
the basename of the given filename.

getDirname

public String getDirname(String filename)
This method gets the directory-name of the given filename (path).
Examples:
filename FileUtil.getDirname(String)
foo .
/foo /
/foo/bar /foo
/foo/bar/ /foo
./foo/bar/ ./foo
./foo/bar/../ ./foo/bar

Specified by:
getDirname in interface FileUtil
Parameters:
filename - is the path to a file or directory.
Returns:
the path to the directory containing the file denoted by the given filename.
See Also:
FileUtil.normalizePath(String)

copyFile

public void copyFile(File source,
                     File destination)
This method copies the file given by source to the file given by destination.

Specified by:
copyFile in interface FileUtil
Parameters:
source - is the existing file to copy from.
destination - is the file to copy to. It will be created if it does NOT exist and overridden otherwise.

copyFile

public void copyFile(File source,
                     File destination,
                     boolean keepFlags)
This method copies the file given by source to the file given by destination.
ATTENTION:
This method will only work with java 1.6 and above!

Specified by:
copyFile in interface FileUtil
Parameters:
source - is the existing file to copy from.
destination - is the file to copy to. It will be created if it does NOT exist and overridden otherwise.
keepFlags - - true if the flags of the file should be copied as well, false otherwise (a new file is created with default flags and only the content is copied).

copyRecursive

public void copyRecursive(File source,
                          File destination,
                          boolean allowOverwrite)
This method copies the file or directory given by source into the given destination.
ATTENTION:
In order to allow giving the copy of source a new name, the destination has to point to the final place where the copy should appear rather than the directory where the copy will be located in.

E.g. the following code copies the folder "foo" located in "/usr/local" recursively to the directory "/tmp". The copy will have the same name "foo".
 File source = new File("/usr/local/foo");
 File destination = new File("/tmp", source.getName()); // file: "/tmp/foo"
 fileUtil.copyRecursive(source, destination, true);
 

Specified by:
copyRecursive in interface FileUtil
Parameters:
source - is the file or directory to copy.
destination - is the final place where the copy should appear.
allowOverwrite - - if false and the destination already exists, a RuntimeIoException is thrown, else if true the destination will be overwritten.

copyRecursive

public void copyRecursive(File source,
                          File destination,
                          boolean allowOverwrite,
                          FileFilter filter)
This method copies the file or directory given by source into the given destination.
ATTENTION:
In order to allow giving the copy of source a new name, the destination has to point to the final place where the copy should appear rather than the directory where the copy will be located in.

Specified by:
copyRecursive in interface FileUtil
Parameters:
source - is the file or directory to copy.
destination - is the final place where the copy should appear.
allowOverwrite - - if false and the destination already exists, a RuntimeIoException is thrown, else if true the destination will be overwritten.
filter - is a FileFilter that decides which files should be copied. Only accepted files and directories are copied, others will be ignored.
See Also:
FileUtil.copyRecursive(File, File, boolean)

copyRecursive

private void copyRecursive(File source,
                           File destination,
                           FileFilter filter)
This method copies the file or directory given by source into the given destination.
ATTENTION:
In order to allow giving the copy of source a new name, the destination has to point to the final place where the copy should appear rather than the directory where the copy will be located in.

E.g. the following code copies the folder "foo" located in "/usr/local" recursively to the directory "/tmp". The copy will have the same name "foo".
 File source = new File("/usr/local/foo");
 File destination = new File("/tmp", source.getName()); // file: "/tmp/foo"
 FileUtilImpl.copyRecursive(source, destination, true);
 

Parameters:
source - is the file or directory to copy.
destination - is the final place where the copy should appear.
filter - is a FileFilter that decides which files should be copied. Only accepted files and directories are copied, others will be ignored.

getPermissions

public FileAccessPermissions getPermissions(File file,
                                            FileAccessClass accessClass)
This method gets the permissions of the given file.
ATTENTION:
This operation is only available since java 6. Further it is limited and can only determine the permissions granted to the current user running this application.

Specified by:
getPermissions in interface FileUtil
Parameters:
file - is the file for which the permissions are requested.
accessClass - is the distinct class the permission should be applied to in the returned permissions. It may be null to apply the permissions to all distinct classes.
Returns:
the permissions of file.

setPermissions

public void setPermissions(File file,
                           FileAccessPermissions permissions)
This method sets the permissions of the given file.
ATTENTION:
This operation is only available since java 6. Further it is limited to the permissions FileAccessClass.OTHERS and FileAccessClass.USER so FileAccessClass.GROUP flags are ignored as well as the global s-bits (sticky, setgid and setuid).

Specified by:
setPermissions in interface FileUtil
Parameters:
file - is the file to modify.
permissions - are the permissions to set.

deleteRecursive

public int deleteRecursive(File path)
This method deletes the given path. If the path denotes a directory then it will be deleted recursively.

Specified by:
deleteRecursive in interface FileUtil
Parameters:
path - is the path to delete.
Returns:
the number of files that have been deleted (excluding the directories).
See Also:
FileUtil.deleteChildren(File)

deleteChildren

public int deleteChildren(File directory)
This method deletes all children of the given directory recursively. If the given directory denotes an existing directory then it will be empty after the call of this method, else this method will have no effect.

Specified by:
deleteChildren in interface FileUtil
Parameters:
directory - is the directory to delete.
Returns:
the number of files that have been deleted (excluding the directories).

getMatchingFiles

public File[] getMatchingFiles(File cwd,
                               String path,
                               FileType fileType)
This method gets all files matching to the given path and fileType. The path may contain wildcards.
Examples:

Specified by:
getMatchingFiles in interface FileUtil
Parameters:
cwd - is the current working directory and should therefore point to an existing directory. If the given path is NOT absolute it is interpreted relative to this directory.
path - is the path the requested files must match. If this path is NOT absolute it is interpreted relative to the directory given by cwd.
fileType - is the type of the requested files or null if files of any type are acceptable.
Returns:
an array containing all the files that match the given path and apply to ignore
See Also:
FileUtil.collectMatchingFiles(File, String, FileType, List)

collectMatchingFiles

public boolean collectMatchingFiles(File cwd,
                                    String path,
                                    FileType fileType,
                                    List<File> list)
This method adds all files matching the given path and fileType to the list. The path may contain wildcards.

Specified by:
collectMatchingFiles in interface FileUtil
Parameters:
cwd - is the current working directory and should therefore point to an existing directory. If the given path is NOT absolute it is interpreted relative to this directory.
path - is the path the files to collect must match. If this path is NOT absolute it is interpreted relative to the directory given by cwd.
fileType - is the type of the files to collect or null if files of any type are acceptable.
list - is the list where to add the collected files.
Returns:
false if the path is a regular string and true if the given path contains at least one wildcard ( '*' or '?').

collectMatchingFiles

private void collectMatchingFiles(File cwd,
                                  FileUtilImpl.PathSegment[] segments,
                                  int segmentIndex,
                                  FileType fileType,
                                  List<File> list)
This method adds all files matching to the given path and fileType to the list. The path may contain wildcards.

Parameters:
cwd - is the current working directory and should therefore point to an existing directory. If the given path is NOT absolute it is interpreted relative to this directory.
segments - is the path the files to collect must match. If this path is NOT absolute it is interpreted relative to the directory given by cwd.
segmentIndex - is the current index in pathChars for the collection process.
fileType - is the type of the files to collect or null if files of any type are acceptable.
list - is the list where to add the collected files.

tokenizePath

private boolean tokenizePath(String path,
                             List<FileUtilImpl.PathSegment> list,
                             PatternCompiler patternCompiler)
This method tokenized the given path by adding FileUtilImpl.PathSegments to the given list.

Parameters:
path - is the path to tokenized
list - is the list where to add the segment tokens.
patternCompiler - is the PatternCompiler used to compile the individual segments of the given path.
Returns:
true if the path is a glob-pattern (contains '*' or '?'), false otherwise.


Copyright © 2001-2010 mmm-Team. All Rights Reserved.