欢迎访问宙启技术站
智能推送

Java函数:如何复制一个文件或文件夹?

发布时间:2023-06-01 09:31:21

复制文件或文件夹是Java编程中的一个基础操作,可以帮助我们在文件系统中创建备份或使用多个副本。Java为复制文件或文件夹提供了许多API方法,包括使用Java IO软件包和Java NIO.2文件API。在本文中,我们将讨论在Java中复制文件或文件夹的几种方法。

1. Java IO软件包

Java IO软件包包含许多用于读取和写入文件的类和接口。复制文件的最简单方法是使用Java IO软件包中的文件输入流和文件输出流来实现。

步骤:

①创建一个新的File对象来表示源文件。

②创建一个新的File对象来表示目标文件或目录。

③创建一个新的输入流对象以从源文件中读取数据。

④创建一个新的输出流对象以将数据写入目标文件。

⑤使用缓冲数组复制源文件中的数据。

⑥在复制完成后关闭输入和输出流。

复制文件示例代码:

import java.io.*;

 

public class CopyFile {

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

        File srcFile = new File("C:/data/source.txt");

        File destFile = new File("C:/data/destination.txt");

 

        try (InputStream in = new FileInputStream(srcFile);

             OutputStream out = new FileOutputStream(destFile)) {

            byte[] buffer = new byte[1024];

            int length;

            while ((length = in.read(buffer)) > 0) {

                out.write(buffer, 0, length);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

复制整个目录:

复制整个目录的方法与复制单个文件或目录的方法类似。 的区别在于我们需要递归调用复制方法,以便复制源目录下的子目录和文件。

我们可以定义一个方法来复制整个目录。这个方法有两个参数,分别是源目录和目标目录。通过递归调用复制方法,我们可以将源目录中的所有文件和目录复制到目标目录中。

复制目录示例代码:

import java.io.*;

 

public class CopyDirectory {

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

        File srcDir = new File("C:/data/source");

        File destDir = new File("C:/data/destination");

 

        copyDirectory(srcDir, destDir);

    }

 

    public static void copyDirectory(File source, File destination) throws IOException {

        if (source.isDirectory()) {  // 如果是目录

            if (!destination.exists()) {

                destination.mkdir();

            }

            String[] children = source.list();

            for (String file : children) {

               copyDirectory(new File(source, file), new File(destination, file));

            }

        } else {  // 如果是文件

            try (InputStream in = new FileInputStream(source);

                    OutputStream out = new FileOutputStream(destination)) {

                byte[] buffer = new byte[1024];

                int length;

                while ((length = in.read(buffer)) > 0) {

                    out.write(buffer, 0, length);

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}

这个示例代码中的copyDirectory()方法使用递归方式将源目录中的文件和目录复制到目标目录中。如果我们想要在复制过程中保留文件和目录的权限和时间戳等元数据,可以使用Java 7中的Files.copy()方法。

2. Java NIO.2文件API

Java NIO.2文件API是Java 7中引入的新功能,它提供了更简单的方法来处理文件系统中的文件和目录。

使用Java NIO.2文件API复制文件的最简单方式是使用Files.copy()方法。该方法有两个参数:源路径和目标路径。此外,我们可以使用StandardCopyOption选项来指定如何复制文件。

复制文件示例代码:

import java.io.*;

import java.nio.file.*;

 

public class CopyFile {

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

        Path srcPath = Paths.get("C:/data/source.txt");

        Path destPath = Paths.get("C:/data/destination.txt");

        

        try {

            Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

复制整个目录:

使用Java NIO.2文件API复制整个目录需要递归地遍历目录树并复制每个文件和子目录。与使用Java IO软件包的方法相似。

复制目录示例代码:

import java.io.*;

import java.nio.file.*;

 

public class CopyDirectory {

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

        Path source = Paths.get("C:/data/source");

        Path destination = Paths.get("C:/data/destination");

         

        copyDirectory(source, destination);

    }

     

    private static void copyDirectory(Path source, Path destination) throws IOException {

        Files.walk(source).forEach(srcPath -> {

            Path destPath = destination.resolve(source.relativize(srcPath));

            try {

                if (Files.isDirectory(srcPath)) {

                    if (!Files.exists(destPath))

                        Files.createDirectory(destPath);

                    return;

                }

                Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING);

            } catch (IOException e) {

                e.printStackTrace();

            }

        });

    }

}

在这个示例代码中,我们使用Files.walk()方法递归从源目录中遍历所有文件和子目录。对于每个文件或子目录,我们使用resolve()方法从目标目录中获取相对路径。然后,我们使用Files.isDirectory()方法来检查当前路径是否是目录。如果是,我们使用Files.createDirectory()方法来创建目录,否则我们使用Files.copy()方法来复制文件。最后,我们使用StandardCopyOption选项指定如何执行文件复制。