日期:2014-05-16  浏览次数:21010 次

apache commons-vfs源码赏析(一)
最近项目中需要用到对不来自与不同的文件系统的文件进行操作,于是就用到apache的commons-vfs这个包.

对于这个包apache是这样介绍的:就是提供对不同的文件系统的文件提供统一的操作.
例如ftp,http,本地文件系统等等.

其实说源码赏析有点过了,就是稍微看了看它的源码

我们可以用svn通过下面的地址
引用

http://svn.apache.org/repos/asf/commons/proper/vfs/trunk
去获取它的源代码.

首先我们来看看它的比较重要的几个类
1.首先比较重要的一个类就是VFS类,这个类位于org.apache.commons.vfs包下
这个类的主要作用就是初始话一个标准的文件系统(StandardFileSystemManager)对象,并调用其init方法,并提过一个获取这个标准文件系统对象的静态方法.
主要的代码:
public static synchronized FileSystemManager getManager()
        throws FileSystemException
    {
        if (instance == null)
        {
            instance = createManager("org.apache.commons.vfs.impl.StandardFileSystemManager");
        }
        return instance;
    }


    private static FileSystemManager createManager(final String managerClassName)
        throws FileSystemException
    {
        try
        {
            // Create instance
            final Class mgrClass = Class.forName(managerClassName);
            final FileSystemManager mgr = (FileSystemManager) mgrClass.newInstance();

            /*
            try
            {
                // Set the logger
                final Method setLogMethod = mgrClass.getMethod("setLogger", new Class[]{Log.class});
                final Log logger = LogFactory.getLog(VFS.class);
                setLogMethod.invoke(mgr, new Object[]{logger});
            }
            catch (final NoSuchMethodException e)
            {
                // Ignore; don't set the logger
            }
            */

            try
            {
                // Initialise
                final Method initMethod = mgrClass.getMethod("init", (Class[]) null);
                initMethod.invoke(mgr, (Object[]) null);
            }
            catch (final NoSuchMethodException e)
            {
                // Ignore; don't initialize
            }

            return mgr;
        }
        catch (final InvocationTargetException e)
        {
            throw new FileSystemException("vfs/create-manager.error",
                managerClassName,
                e.getTargetException());
        }
        catch (final Exception e)
        {
            throw new FileSystemException("vfs/create-manager.error",
                managerClassName,
                e);
        }
    }


我们在使用commons-vfs时一般都是通过这个类先获取这个公用的文件系统接口,所有对于各种文件系统的操作都是基于这个接口来实现.
如:
  FileSystemManager fsm = VFS.getManager();