题目:设计一个Java程序,实现文件复制功能。
要求:
创建一个文件复制类(FileCopy),具有以下功能: a. 复制单个文件; b. 复制整个文件夹(包括子文件夹和文件夹中的文件); c.
在复制过程中,显示复制的进度百分比。 使用面向对象的思想,设计合适的类和方法来实现上述功能。
给出注释和代码说明,解释代码的执行过程和复制过程中的逻辑。
示例代码:
import java.io.*;
// 文件复制类
class FileCopy {
public void copyFile(String srcPath, String destPath) {
File srcFile = new File(srcPath);
File destFile = new File(destPath);
try (InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int length;
long fileSize = srcFile.length();
long copiedSize = 0; // 已复制的文件大小
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length); // 写入目标文件
copiedSize += length;
int progress = (int) ((double) copiedSize / fileSize * 100); // 计算进度百分比
System.out.println("复制进度:" + progress + "%");
}
System.out.println("文件复制成功!");
} catch (IOException e) {
System.out.println("文件复制失败:" + e.getMessage());
}
}
public void copyFolder(String srcFolderPath, String destFolderPath) {
File srcFolder = new File(srcFolderPath);
File destFolder = new File(destFolderPath);
if (!srcFolder.exists() || !srcFolder.isDirectory()) {
System.out.println("源文件夹不存在或不是文件夹!");
return;
}
if (!destFolder.exists()) {
destFolder.mkdirs();
}
File[] files = srcFolder.listFiles();
for (File file : files) {
if (file.isFile()) {
String srcFilePath = file.getAbsolutePath();
String destFilePath = destFolderPath + File.separator + file.getName();
copyFile(srcFilePath, destFilePath); // 对每个文件调用copyFile方法进行复制
} else if (file.isDirectory()) {
String srcSubFolderPath = file.getAbsolutePath();
String destSubFolderPath = destFolderPath + File.separator + file.getName();
copyFolder(srcSubFolderPath, destSubFolderPath); // 对子文件夹递归调用copyFolder方法进行复制
}
}
}
}
public class Main {
public static void main(String[] args) {
FileCopy fileCopy = new FileCopy();
// 复制单个文件
String srcFilePath = "path/to/source/file.txt";
String destFilePath = "path/to/destination/file.txt";
fileCopy.copyFile(srcFilePath, destFilePath);
// 复制整个文件夹
String srcFolderPath = "path/to/source/folder";
String destFolderPath = "path/to/destination/folder";
fileCopy.copyFolder(srcFolderPath, destFolderPath);
}
}
解释和代码注释:
文件复制类(FileCopy)使用InputStream和OutputStream来实现文件的复制,通过读取源文件内容,写入目标文件,实现复制文件的功能。在复制过程中,通过计算已复制的文件大小与总文件大小的比例,计算复制的进度百分比,并进行显示。
复制文件的方法copyFile()接收源文件路径和目标文件路径作为参数,通过创建FileInputStream读取源文件,创建FileOutputStream写入目标文件,在循环读取和写入的过程中,每次循环结束计算复制进度并进行显示,直到文件复制完成。
复制文件夹的方法copyFolder()接收源文件夹路径和目标文件夹路径作为参数,首先判断源文件夹是否存在,并且目标文件夹不存在则创建新文件夹。然后通过调用listFiles()方法得到源文件夹中的文件和子文件夹的数组,遍历数组,如果是文件,则调用copyFile()方法复制文件;如果是子文件夹,则递归调用copyFolder()方法复制子文件夹。
主函数中,首先创建一个文件复制类的对象,然后分别调用copyFile()方法和copyFolder()方法来复制文件和文件夹。
通过这个题目,可以练习以下Java知识点:
文件的读取和写入; 异常处理(使用try-catch-finally块进行文件的关闭操作);
文件和文件夹的操作(包括判断文件是否存在、创建文件夹等); 递归调用方法处理复杂的文件夹结构; 进度显示和百分比计算。
通过这道题目可以学到如何实现文件复制功能,并且了解到在实际开发中,文件复制是常见的操作之一。