Java文件复制及文件夹复制示例:从入门到实践

  • 发布时间:2023-09-13 21:52:23
  • 本文热度:浏览 622 赞 0 评论 0
  • 全文共1字,阅读约需1分钟

1. Java复制文件

在开发过程中,我们经常需要处理文件相关的操作,其中包括文件的复制。Java提供了多种方法来实现文件的复制,本篇将介绍如何使用Java复制文件和文件夹。

1.1 复制文件

首先,我们来看下如何在Java中复制一个文件。Java的文件操作主要通过java.io包下的File类来实现。

1.1.1 方法一:使用字节流

一个简单的方法是使用字节流来读取源文件,并将读取的内容写入到目标文件中。下面是一个示例代码:

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

public class FileCopyExample {
    public static void copyFile(String sourceFilePath, String targetFilePath) throws IOException {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(sourceFilePath);
            fos = new FileOutputStream(targetFilePath);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }

    public static void main(String[] args) {
        String sourceFilePath = "path/to/source/file.txt";
        String targetFilePath = "path/to/target/file.txt";
        try {
            copyFile(sourceFilePath, targetFilePath);
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            System.out.println("文件复制失败:" + e.getMessage());
        }
    }
}

上述代码通过FileInputStreamFileOutputStream来读取和写入文件内容,通过定义一个缓冲区buffer来存储读取的字节数据,并且每次读取固定长度的字节数据,直到读取完整个文件。

1.1.2 方法二:使用字符流

另一种方法是使用字符流来复制文件。这种方式适合处理文本文件,可以更好地保留文件的编码格式和字符的完整性。下面是一个示例代码:

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileCopyExample {
    public static void copyFile(String sourceFilePath, String targetFilePath) throws IOException {
        FileReader reader = null;
        FileWriter writer = null;

        try {
            reader = new FileReader(sourceFilePath);
            writer = new FileWriter(targetFilePath);
            char[] buffer = new char[1024];
            int length;
            while ((length = reader.read(buffer)) > 0) {
                writer.write(buffer, 0, length);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

    public static void main(String[] args) {
        String sourceFilePath = "path/to/source/file.txt";
        String targetFilePath = "path/to/target/file.txt";
        try {
            copyFile(sourceFilePath, targetFilePath);
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            System.out.println("文件复制失败:" + e.getMessage());
        }
    }
}

上述代码通过FileReaderFileWriter来读取和写入文件内容,并且与字节流的方法类似,也使用了缓冲区buffer来存储读取的字符数据,并按照固定长度将字符数据写入目标文件。

1.2 复制文件夹

除了复制单个文件,有时候我们也需要复制整个文件夹及其子文件夹和文件。Java提供了递归方式来处理文件夹的复制。

1.2.1 方法一:自定义递归

下面是一个使用自定义递归方法来复制文件夹的示例代码:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class FolderCopyExample {
    public static void copyFolder(File sourceFolder, File targetFolder) throws IOException {
        if (sourceFolder.isDirectory()) {
            if (!targetFolder.exists()) {
                targetFolder.mkdirs();
            }
            String[] files = sourceFolder.list();
            if (files != null) {
                for (String file : files) {
                    File srcFile = new File(sourceFolder, file);
                    File tgtFile = new File(targetFolder, file);
                    copyFolder(srcFile, tgtFile);
                }
            }
        } else {
            Files.copy(sourceFolder.toPath(), targetFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
    }

    public static void main(String[] args) {
        String sourceFolderPath = "path/to/source/folder";
        String targetFolderPath = "path/to/target/folder";
        File sourceFolder = new File(sourceFolderPath);
        File targetFolder = new File(targetFolderPath);
        try {
            copyFolder(sourceFolder, targetFolder);
            System.out.println("文件夹复制成功!");
        } catch (IOException e) {
            System.out.println("文件夹复制失败:" + e.getMessage());
        }
    }
}

上述代码使用递归的方式来复制文件夹。如果遇到子文件夹,则递归调用copyFolder方法来复制子文件夹及其下的文件。如果遇到文件,则使用Files.copy方法来复制文件。

1.2.2 方法二:使用Apache Commons IO库

除了自定义递归方法外,我们还可以使用第三方库来实现文件夹的复制。Apache Commons IO是一个常用的Java开源库,提供了丰富的文件操作方法。下面是使用Apache Commons IO库中的FileUtils类来复制文件夹的示例代码:

首先,需要添加Apache Commons IO库的依赖:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

然后,可以使用下面的代码来复制文件夹:

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class FolderCopyExample {
    public static void copyFolder(File sourceFolder, File targetFolder) throws IOException {
        if (sourceFolder.isDirectory()) {
            if (!targetFolder.exists()) {
                targetFolder.mkdirs();
            }
            FileUtils.copyDirectory(sourceFolder, targetFolder);
        } else {
            FileUtils.copyFile(sourceFolder, targetFolder);
        }
    }

    public static void main(String[] args) {
        String sourceFolderPath = "path/to/source/folder";
        String targetFolderPath = "path/to/target/folder";
        File sourceFolder = new File(sourceFolderPath);
        File targetFolder = new File(targetFolderPath);
        try {
            copyFolder(sourceFolder, targetFolder);
            System.out.println("文件夹复制成功!");
        } catch (IOException e) {
            System.out.println("文件夹复制失败:" + e.getMessage());
        }
    }
}

上述代码使用了FileUtils.copyDirectory方法来复制文件夹,如果遇到文件,则使用FileUtils.copyFile方法来复制文件。

1.3 总结

本篇博客介绍了在Java中如何复制文件和文件夹。对于文件的复制,可以使用字节流或字符流来实现。对于文件夹的复制,可以使用自定义递归方法或使用第三方库如Apache Commons IO来实现。

正文到此结束
评论插件初始化中...
Loading...