广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >java复制文件的4种方实例
  • 433
分享到

java复制文件的4种方实例

java 2017-09-24 00:09:51 433人浏览 无得
摘要

java复制文件的4种方法:(推荐:java视频教程)一、使用FileStreams复制这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件

java复制文件的4种方法:(推荐:java视频教程

一、使用FileStreams复制

这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B。 这是第一个方法的代码:

private static void copyFileUsingFileStreams(File source, File dest)
        throws ioException {    
    InputStream input = null;    
    OutputStream output = null;    
    try {
           input = new FileInputStream(source);
           output = new FileOutputStream(dest);        
           byte[] buf = new byte[1024];        
           int bytesRead;        
           while ((bytesRead = input.read(buf)) != -1) {
               output.write(buf, 0, bytesRead);
           }
    } finally {
        input.close();
        output.close();
    }
}

正如你所看到的我们执行几个读和写操作try的数据,所以这应该是一个低效率的,下一个方法我们将看到新的方式。

二、使用FileChannel复制

Java NIO包括transferFrom方法,根据文档应该比文件流复制的速度更快。 这是第二种方法的代码:

private static void copyFileUsingFileChannels(File source, File dest) throws IOException {    
        FileChannel inputChannel = null;    
        FileChannel outputChannel = null;    
    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}

三、使用Commons IO复制

Apache Commons IO提供拷贝文件方法在其FileUtils类,可用于复制一个文件到另一个地方。它非常方便使用Apache Commons FileUtils类时,您已经使用您的项目。基本上,这个类使用Java NIO FileChannel内部。 这是第三种方法的代码:

private static void copyFileUsingApacheCommonsIO(File source, File dest)
         throws IOException {
     FileUtils.copyFile(source, dest);
 }

该方法的核心代码如下:

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 > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : 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());
        }
    }

由此可见,使用Apache Commons IO复制文件的原理就是上述第二种方法:使用FileChannel复制

四、使用Java7的Files类复制

如果你有一些经验在Java 7中你可能会知道,可以使用复制方法的Files类文件,从一个文件复制到另一个文件。 这是第四个方法的代码:

 private static void copyFileUsingJava7Files(File source, File dest)
         throws IOException {    
         Files.copy(source.toPath(), dest.toPath());
 }

五、测试

现在看到这些方法中的哪一个是更高效的,我们会复制一个大文件使用每一个在一个简单的程序。 从缓存来避免任何性能明显我们将使用四个不同的源文件和四种不同的目标文件。 让我们看一下代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import org.apache.commons.io.FileUtils;

public class CopyFilesExample {

    public static void main(String[] args) throws InterruptedException,
            IOException {

        File source = new File("C:\Users\nikos7\Desktop\files\sourcefile1.txt");
        File dest = new File("C:\Users\nikos7\Desktop\files\destfile1.txt");

        // copy file using FileStreamslong start = System.nanoTime();
        long end;
        copyFileUsingFileStreams(source, dest);
        System.out.println("Time taken by FileStreams Copy = "
                + (System.nanoTime() - start));

        // copy files using java.nio.FileChannelsource = new File("C:\Users\nikos7\Desktop\files\sourcefile2.txt");
        dest = new File("C:\Users\nikos7\Desktop\files\destfile2.txt");
        start = System.nanoTime();
        copyFileUsingFileChannels(source, dest);
        end = System.nanoTime();
        System.out.println("Time taken by FileChannels Copy = " + (end - start));

        // copy file using Java 7 Files classsource = new File("C:\Users\nikos7\Desktop\files\sourcefile3.txt");
        dest = new File("C:\Users\nikos7\Desktop\files\destfile3.txt");
        start = System.nanoTime();
        copyFileUsingJava7Files(source, dest);
        end = System.nanoTime();
        System.out.println("Time taken by Java7 Files Copy = " + (end - start));

        // copy files using apache commons iosource = new File("C:\Users\nikos7\Desktop\files\sourcefile4.txt");
        dest = new File("C:\Users\nikos7\Desktop\files\destfile4.txt");
        start = System.nanoTime();
        copyFileUsingApacheCommonsIO(source, dest);
        end = System.nanoTime();
        System.out.println("Time taken by Apache Commons IO Copy = "
                + (end - start));

    }

    private static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }

    private static void copyFileUsingFileChannels(File source, File dest)
            throws IOException {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }
    }

    private static void copyFileUsingJava7Files(File source, File dest)
            throws IOException {
        Files.copy(source.toPath(), dest.toPath());
    }

    private static void copyFileUsingApacheCommonsIO(File source, File dest)
            throws IOException {
        FileUtils.copyFile(source, dest);
    }

}

输出:

Time taken by FileStreams Copy = 127572360
Time taken by FileChannels Copy = 10449963
Time taken by Java7 Files Copy = 10808333
Time taken by Apache Commons IO Copy = 17971677

正如您可以看到的FileChannels拷贝大文件是最好的方法。如果你处理更大的文件,你会注意到一个更大的速度差。

更多java知识请关注Java基础教程栏目。

--结束END--

本文标题: java复制文件的4种方实例

本文链接: https://www.lsjlt.com/news/1764.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • java复制文件的4种方实例
    java复制文件的4种方法:(推荐:java视频教程)一、使用FileStreams复制这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件...
    99+
    2017-09-24
    java
  • java复制文件的4种方式
     1. 使用FileStreams复制  这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B。  这是第一个方法的代码:  privat...
    99+
    2023-06-03
  • Java文件复制多种方法
    InputStream与OutputStream  创建两个文件 - 源和目标。然后我们从源创建InputStream并使用OutputStream将其写入目标文件进行 java 复制文件操作。 private static void ...
    99+
    2023-10-27
    java jvm c++
  • Java下载文件的4种方式总结
    1. 使用URL类的openStream()方法:这是最基本的下载文件的方式。通过URL.openStream()方法,可以获取到文件的输入流,然后使用输入流的read()方法来读取文件内容,并将其写入到本地文件中。2. 使用URLCo...
    99+
    2023-08-09
    Java
  • Mybatis分页的4种方式实例
    数组分页 查询出全部数据,然后再list中截取需要的部分。 mybatis接口 List<Student> queryStudentsByArray(); xml配置文件...
    99+
    2022-11-13
  • Java 实现文件复制及文件夹复制
    在Java中,有多种方法可以实现文件的复制。以下是几种常用的方式: 使用字节流进行复制: 通过FileInputStream和FileOutputStream分别创建源文件和目标文件的输入输出流,然后通过循环读取源文件内容,并将数据写入目标...
    99+
    2023-09-26
    java 开发语言
  • java中的4种循环方法示例详情
    目录java循环结构1.while循环2.do…while循环3.for循环4.java 增强for循环java循环结构 顺序结构的程序语句只能 被执行一次。如果你要同样的操作执行多...
    99+
    2022-11-12
  • Node.js复制文件的方法示例
    本文实例讲述了Node.js复制文件的方法。分享给大家供大家参考,具体如下: 本人开发过程中,经常遇到,要去拷贝模板到当前文件夹,经常要去托文件,为了省事,解决这个问题,写了一个node复制文件。 //...
    99+
    2022-06-04
    示例 文件 方法
  • SpringBoot读取Resource下文件的4种方法
    SpringBoot读取Resource下文件 最近在项目中涉及到Excle的导入功能,通常是我们定义完模板供用户下载,用户按照模板填写完后上传;这里待下载模板位置为resource...
    99+
    2022-11-12
  • Shell逐行读取文件的4种方法
    在Linux中有很多方法逐行读取一个文件的方法,其中最常用的就是下面的脚本里的方法,而且是效率最高,使用最多的方法。为了给大家一个直观的感受,我们将通过生成一个大的文件的方式来检验各种方法的执行效率。 方...
    99+
    2022-06-04
    种方法 文件 Shell
  • 用Shell实现逐行读取文件的4种方法
    这篇文章主要介绍“用Shell实现逐行读取文件的4种方法”,在日常操作中,相信很多人在用Shell实现逐行读取文件的4种方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”用Shell实现逐行读取文件的4种方法...
    99+
    2023-06-09
  • Java实现文件或文件夹的复制到指定目录实例
    整理文档,搜刮出一个Java实现文件或文件夹的复制到指定目录的代码,稍微整理精简一下做下分享。import java.io.File; import java.io.FileInputStream; import java.io.FileO...
    99+
    2023-05-31
    java 文件 复制
  • Java实现定时器的4种方法
    Java实现定时器的4种方法:1. 使用Timer类:Timer类是Java提供的一个定时器工具类,可以用它创建计划任务,可以一次性...
    99+
    2023-08-08
    Java
  • list的4种遍历方式(实例讲解)
    废话不多说,直接上代码:import java.util.ArrayList;import java.util.Iterator;import java.util.List;import com.hbut.domain.Person;pub...
    99+
    2023-05-31
    list 遍历方式 lis
  • 在Node.js中实现文件复制的方法和实例
    Node.js 本身并没有提供直接复制文件的 API,如果想用 Node.js 复制文件或目录,需要借助其他的 API 来实现。复制单个的文件可以直接用 readFile、writeFile,这样比较简便。...
    99+
    2022-06-04
    实例 文件 方法
  • Java之线程编程的4种方法实现案例讲解
    1、继承Thread public class T4 { public static void main(String[] args) { System.out.print...
    99+
    2022-11-12
  • php文件包含的4种方式是什么
    php文件包含的4种方式是:1、require()语句。2、include()语句。3、require_once()语句。4、include_once()语句。require()语句require()语句类似C语言中的include()语句...
    99+
    2022-10-24
  • Python字符串拼接的4种方法实例
    目录1. 算术运算符拼接(1)+算术运算符(2) * 算术运算符2、format方法3、百分号操作符4、特殊符号f附:常见字符串去除空格的方法总结总结在程序实际应用中,少不了要进行字...
    99+
    2022-11-11
  • java异步调用的4种实现方法
    目录一.利用多线程直接new线程使用线程池二.采用Spring 的异步方法去执行(无返回值)@Async注解可以用在方法上,也可以用在类上,用在类上,对类里面所有方法起作用三.采用S...
    99+
    2022-11-13
  • Linux中删除文件内空行的4种方法
    在Linux上处理一些数据文件时,有时候需要将其中的空行过滤掉,系统中提供的各种工具都可以完成这个功能。将常用的介绍如下吧:1. grep grep . data.txtgrep -v '^$' data....
    99+
    2022-06-04
    空行 种方法 文件
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作