开发者

Java的几种文件拷贝方式示例详解

目录
  • 一、使用传统的FileInputStream和FileOutputStream实现文件的拷贝
  • 二、利用 Java.nio 包下的库,使用 transferTo 或 transfFrom 方法实现
  • 三、使用Java 标准类库本身已经提供了 Files.copy
  • 总结

一、使用传统的FileInputStream和FileOutputStream实现文件的拷贝

使用传统的FileInputStream和FileOutputStream实现文件拷贝是Java I/O流操作中最基本的方法之一。这种编程客栈方式使用字节流直接读取源文件内容,并写入目标文件,适用于文本文件和二进制文件

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyWithStreams {
    public static void main(String[] args) {
        String sourceFile = "source.txt"; // 源文件路径
        String destinationFile = "destination.txt"; // 目标文件路径

        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(sourceFile);
            fos = new FileOutputStream(destinationFile);
            byte[] buffer = new byte[1024]; // 创建缓冲区
            int length;

            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }

            System.out.println("File copied successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流,先检查是否为null
            try {
                if (fis != null) fis.close();
                if (fos != null)rjIIixYPw fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用FileInputStream和FileOutputStream是实现文件拷贝的一种直观且简单的方法,尽管它不如NIO提供的Files.copy方法高效,但在某些情况下仍然非常有用。

二、利用php java.nio 包下的库,使用 transferTo 或 transfFrom 方法实现

transferFrom、 transferTo 方法可以在文件通道之间直接传输数据,是一种零拷贝的方式来实现文件的拷贝

public class NIOFileChannel04 {
    public static void main(String[] args)  throws Exception {

        //创建相关流
        FileInputStream fileInputStream = new FileInputStream("d:\\a.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\a2.jpg");

        //获取各个流对应的filechannel
        FileChannel sourceCh = fileInputStream.getChannel();
        FileChannel destCh = fileOutputStream.getChannel();

        //使用transferForm完成拷贝
        destCh.transferFrom(sourceCh,0,sourceCh.size());
        //关闭相关通道和流
        sourceCh.close();
        destCh.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileCopyWithTransferTo {
    public static void main(String[] args) {
        String sourcePath = "source.txt";
        String destinationPath = "destination.txt";
        
        try (FileInputStream fis = new FileInputStream(sourcePath);
             FileOutputStream fos = new FileOutputStream(destinationPath);
             FileChannel sourceChannel = fis.getChannel();
             FileChannel destinationChannel = fos.getChannel()) {
            
            // 使用 transferTo 方法传输数据
            sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
            
            System.out.println("File copied successfully.");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("File copying failed.");
        }
    }
}

在上面的代码中,我们使用 FileInputStream 和 FileOutputStream 分别打开源文件和目标文件。然后,通过调用 getChannel 方法获取它们对应的 FileChannel。接着,我们调用 transferTo 方法来直接将源文件的数据传输到目标文件中。

这里的 transferTo 方法会将源通道的数据传输到目标通道中,直到源通道的末尾。这个方法是零拷贝的一种典型应用,它能够高效地将编程客栈数据从一个通道传输到另一个通道,而不需要在用户空间和内核空间之间进行数据复制。

使用 transferTo 方法进行文件拷贝是一种高效且简洁的方式,特别适用于大文件的拷贝操作。需要注意的是,在某些操作系统和文件系统中,transferTo 方法可能会限制传输的最大字节数,因此在实际使用中可能需要进行分块传输。

三、使用Java 标准类库本身已经提供了 Files.copy

使用Java的Files.copy方法可以非常方便地实现文件的拷贝,这是Java NIO Files类提供的一种简洁方式

以下是如何使用Files.copy方法来拷贝文件的示例:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FilesCopyExample {
    public static void main(String[] args) {
        // 指定源文件和目标文件的路径
        Path sourcePath = Paths.get("source.txt");
        Path destinationPath = Paths.get("destination.txt");
       javascript 
        try {
            // 使用Files.copy拷贝文件
            Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File copied successfully.");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("File copying failed.");
        }
    }
}

注意事项:

  • 异常处理:Files.copy方法可能会抛出IOException,因此需要捕获或者声明抛出这个异常。
  • 替换现有文件:通过指定StandardCopyOption.REPLACE_EXISTING作为参数,可以实现如果目标文件已经存在则替换它;如果不希望替换,可以去掉这个选项,但要注意处理文件已存在的情况。
  • 文件属性:使用Files.copy方法还可以选择保留文件属性等,通过传入其他CopyOption实现。

    使用Files.copy方法进行文件拷贝是一种简单且强大的方式,特别适合那些不需要低级文件控制的场景。

Files.copy是零拷贝吗?

Files.copy方法在Java中是用来复制文件的一种高级操作,它是基于Java NIO(New Input/Output)的文件API实现的。虽然这个方法提供了一个简洁的方式来复制文件,但它本身并不实现零拷贝(zero-copy)技术。

总结

到此这篇关于Java的几种文件拷贝方式的文章就介绍到这了,更多相关Java文件拷贝方式内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜