`
zhouxianglh
  • 浏览: 266346 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

源代码分析commons-io-2.0.1-src (一)

    博客分类:
  • J2SE
阅读更多

Commons 是Apache 的一个开源项目,提供了一些由apache为JDK补充的类和方法.

Commons 网址 http://commons.apache.org/   这里就分析最基础的Commons-io-2.0.1

相关API http://commons.apache.org/io/api-release/index.html

这里分析一些认为比较好的代码.

 

1 org.apache.commons.io.FileUtils.java中FileChannel的使用

 /**
     * 使用FileChannel复制文件<br>
     * Internal copy file method.
     * 
     * @param srcFile  the validated source file, must not be <code>null</code>
     * @param destFile  the validated destination file, must not be <code>null</code>
     * @param preserveFileDate  是否保留原最后修改时间<br>whether to preserve the file date
     * @throws IOException if an error occurs
     */
 private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel input = null;
        FileChannel output = null;
        try {
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            input  = fis.getChannel();
            output = fos.getChannel();
            long size = input.size();
            long pos = 0;
            long count = 0;
            while (pos < size) {
                count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
                pos += output.transferFrom(input, pos, count);
            }
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(fis);
        }

        if (srcFile.length() != destFile.length()) {
            throw new IOException("Failed to copy full contents from '" +
                    srcFile + "' to '" + destFile + "'");
        }
        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
    }

 这里主要注意java.nio.channels.FileChannel.

相关文章

http://wlh269.iteye.com/blog/474068   这个主要讲了使用FileChannel锁定文件.需要补充的是FileChannel锁定文件必需要的文件可写入操作,如果代码中RandomAccessFile 用FileInputStream代替则会抛出

Exception in thread "main" java.nio.channels.NonWritableChannelException
	at sun.nio.ch.FileChannelImpl.tryLock(Unknown Source)
	at java.nio.channels.FileChannel.tryLock(Unknown Source)

 异常.用FileOutputStream代替则可正常运行.

http://www.iteye.com/topic/667457   这里作者试着用FileChannel执行文件的复制操作,这和这里的方法不谋而合.有人提到新的jdk中普通io已经用nio重新实现了一遍,那里的代码还没有认真分析,不知是不是这么回事.抛砖引玉http://www.iteye.com/topic/668311 进一步分析了这部分内容.可以参考.

 

2 org.apache.commons.io.FileUtils.java中关于try.....catch.....finally的使用

    /**
     * 通过字节流的方式从InputStream复制文件到指定文件,如果目标文件不存在则创建,如果存在则覆盖<br>
     * Copies bytes from an {@link InputStream} <code>source</code> to a file
     * <code>destination</code>. The directories up to <code>destination</code>
     * will be created if they don't already exist. <code>destination</code>
     * will be overwritten if it already exists.
     *
     * @param source  the <code>InputStream</code> to copy bytes from, must not be <code>null</code>
     * @param destination  the non-directory <code>File</code> to write bytes to
     *  (possibly overwriting), must not be <code>null</code>
     * @throws IOException if <code>destination</code> is a directory
     * @throws IOException if <code>destination</code> cannot be written
     * @throws IOException if <code>destination</code> needs creating but can't be
     * @throws IOException if an IO error occurs during copying
     * @since Commons IO 2.0
     */
    public static void copyInputStreamToFile(InputStream source, File destination) throws IOException {
        try {
            FileOutputStream output = openOutputStream(destination);
            try {
            	//将OutputStream复制到InputStream大文件(超过2GB),这个方法已经使用了缓存,所以不再需要缓存 如果文件大小超过2GB,则返回-1
                IOUtils.copy(source, output);
            } finally {
                IOUtils.closeQuietly(output);
            }
        } finally {
            IOUtils.closeQuietly(source);
        }
    }

  注意这里的try...finally  因为FileUtils是工具类,所以它不处理这些异常,但为了保证文件被正常关闭,这里使用了try...finally而没有捕捉异常.异常交给调用方法处理.

 

3 org.apache.commons.io.FileUtils.java中关于网络编程的支持

	@Test
	public void testCopyURLToFile() {
		URL sourceUrl = null;
		// String urlPath = "http://www.google.com";
		// String urlPath = "ftp://zhouxiang:good@127.0.0.1/FTP专用目录(server-U).txt";
		//此链接即上一链接,通过谷歌浏览器获取,因为包含中文,因此需要转码
		String urlPath = "ftp://zhouxiang:good@127.0.0.1/FTP%E4%B8%93%E7%94%A8%E7%9B%AE%E5%BD%95(server-U).txt";
		try {
			urlPath = URLDecoder.decode(urlPath, "UTF-8");
			System.out.println("Request: "+urlPath);
			sourceUrl = new URL(urlPath);
			File file = new File(TEST_FILE_PATH);//TEST_FILE_PATH 下载文件路径
			System.out.println("Old last modified time " + new Date(file.lastModified()));
			FileUtils.copyURLToFile(sourceUrl, file);//org.apache.commons.io.FileUtils
			System.out.println("Now last modified time " + new Date(file.lastModified()));
			System.out.println("file size " + file.length());
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

  这里使用org.apache.commons.io.FileUtils.copyURLToFile(URL source, File destination) throws IOException访问网络内容.具体操作可参考其源代码.

分享到:
评论

相关推荐

    源代码分析commons-io-2.0.1-src (二)

    《源代码分析commons-io-2.0.1-src (二)》 Apache Commons IO库是Java开发者常用的工具库,主要用于处理各种输入/输出操作。在本文中,我们将深入探讨其2.0.1版本的源代码,特别是关注其设计模式、核心功能以及实现...

    commons-io-2.0.1

    Apache Commons IO 2.0.1 版本是该库的一个稳定版本,它包含了从早期版本中积累的各种改进和修复。这个版本提供了大量静态工厂方法来创建InputStream、OutputStream、Reader、Writer等流对象,以及用于处理文件、...

    commons-fileupload-1.2.2 common-io-2.0.1

    `commons-fileupload-1.2.2-bin.zip`包含编译好的库文件,可以直接在项目中使用,而`commons-fileupload-1.2.2-src.zip`则包含源代码,便于开发者查看或自定义实现。 **Apache Commons IO** 是另一个非常有用的库,...

    commons-io-2.0.1.jar中文-英文对照文档.zip

    源代码下载地址:【***-sources.jar下载地址(官方地址+国内镜像地址).txt】 # 本文件关键字: 中文-英文对照文档,中英对照文档,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,...

    基于SSM框架的在线云盘+源代码+文档说明

    commons-io-2.0.1.jar mysql-connector-java-5.1.32.jar druid-1.0.9jar &lt;项目介绍&gt; 该资源内项目源码是个人的毕设,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! 1、该资源内...

    selenium httpunit测试程序

    2011-10-06 13:42 159,509 commons-io-2.0.1.jar 2011-10-06 13:42 299,994 commons-jxpath-1.3.jar 2011-10-06 13:42 284,220 commons-lang-2.6.jar 2011-10-06 13:42 60,686 commons-logging-1.1.1.jar 2011-10-06...

    word文档专用

    4. **目录结构的规划**:明确项目的目录结构,例如`src/main/webapp`用于存放前端资源文件,`src/main/java`用于存放Java源代码等。 #### 二、引入JAR包 在Java Web开发中,经常需要使用到各种第三方库来增强项目...

    struts2需要的jar包汇总

    7. **commons-io-2.0.1.jar**:Apache Commons IO库,提供了许多与输入/输出相关的实用工具类,如文件操作、流操作等,方便在处理文件时进行读写操作。 8. **commons-fileupload-1.2.2.jar**:Apache Commons ...

    Spring集成Struts与Hibernate入门详解

    * commons-io-2.0.1.jar * commons-lang-2.5.jar * commons-logging-1.1.1.jar * freemarker-2.3.16.jar * javassist-3.11.0.GA.jar * ognl-3.0.1.jar * org.springframework.asm-3.1.1.RELEASE.jar * org.spring...

    struts2综合笔记

    - **src**: 包含 Struts2 框架的全部源代码。 #### 五、深入理解 Struts2 - **灵活度**: - Struts2 的知识点虽然分散,但其灵活性和扩展性非常强。 - **开发实践**: - 了解 Struts2 如何与 Spring、Hibernate 等...

    徒手配置Struts2

    - commons-io-2.0.1.jar - commons-lang-2.5.jar - commons-fileupload-1.2.2.jar #### 三、关键配置文件内容 1. **web.xml文件配置** ```xml &lt;web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:...

    ckeditor3.35+ckfinder2.1_jar.rar

    2. `commons-io-2.0.1.jar`:Apache Commons IO库,提供了一系列实用的I/O操作工具类,如文件读写、流处理等。 3. `activation-1.1.jar`:JavaBeans Activation Framework,用于处理和识别MIME类型的数据。 4. `...

    ssh 整合案例及所需jar包

    - `commons-io-2.0.1.jar`: IO操作工具类。 - `commons-lang3-3.1.jar`: 通用语言工具类。 - `freemarker-2.3.19.jar`: 模板引擎。 - `ognl-3.0.5.jar`: OGNL表达式语言。 - `mysql-connector-java-5.1.18-bin....

    luckyGeek:WebCommic(最新图片)> PDF转换器(历史记录)-开源

    4. commons-io-2.0.1.jar:Apache Commons IO库,提供了一系列操作文件和流的实用工具类。 5. im4java-1.2.0-1.5.jar:这是一个用于Java的图像处理库,支持与各种外部图像处理工具(如ImageMagick)的交互。 6. ...

    ssh项目环境搭建步骤(web项目)

    Struts2是一个开放源代码的MVC框架,用于构建Web应用程序。其主要步骤包括: 1. 拷贝必要的Struts2的jar包到项目的lib目录下。这些jar包包括但不限于: - struts2-core-*.*.*.*.jar:Struts2框架核心包。 - xwork...

Global site tag (gtag.js) - Google Analytics