编程怎么复制文件夹里的内容

时间:2025-01-27 22:44:29 网络游戏

在编程中,复制文件夹里的内容可以通过多种方法实现。以下是几种常见的方法:

方法一:使用Java的`File`类和`Scanner`类

```java

import java.io.*;

import java.util.Scanner;

public class Test {

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

Scanner sc = new Scanner(System.in);

System.out.println("输入源文件夹路径:");

File source = new File(sc.next());

System.out.println("输入目标文件夹路径:");

File dest = new File(sc.next());

if (source.isDirectory()) {

copyDirectoryContents(source, dest);

} else {

System.out.println("源路径不是一个文件夹。");

}

}

public static void copyDirectoryContents(File source, File dest) throws IOException {

if (!dest.exists()) {

dest.mkdir();

}

for (File file : source.listFiles()) {

if (file.isDirectory()) {

copyDirectoryContents(file, new File(dest, file.getName()));

} else {

try (FileInputStream fis = new FileInputStream(file);

FileOutputStream fos = new FileOutputStream(new File(dest, file.getName()))) {

byte[] buffer = new byte;

int length;

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

fos.write(buffer, 0, length);

}

}

}

}

}

}

```

方法二:使用Java的`Files`类

```java

import java.io.IOException;

import java.nio.file.*;

import java.nio.file.attribute.BasicFileAttributes;

import java.util.Scanner;

public class Test04_FileCopy {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("请输入源文件(夹)名(绝对路径):");

Path src = Paths.get(input.nextLine());

while (true) {

System.out.println("请输入目标文件夹名(绝对路径):");

Path dest = Paths.get(input.nextLine());

if (Files.isDirectory(dest)) {

copyDirectoryContents(src, dest);

break;

} else {

System.out.println("目标路径不是一个目录,请重新输入。");

}

}

}

public static void copyDirectoryContents(Path src, Path dest) throws IOException {

Files.walkFileTree(src, new SimpleFileVisitor() {

@Override

public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

Files.copy(file, dest.resolve(src.relativize(file)), StandardCopyOption.REPLACE_EXISTING);

return FileVisitResult.CONTINUE;

}

@Override

public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {

return FileVisitResult.CONTINUE;

}

});

}

}

```

方法三:使用C的`Process`类调用DOS命令

```csharp

using System;

class Program {

static void Main() {

Console.WriteLine("请输入源文件(夹)名(绝对路径):");

string source = Console.ReadLine();

Console.WriteLine("请输入目标文件夹名(绝对路径):");

string dest = Console.ReadLine();

string command = $"xcopy \"{source}\" \"{dest}\" /E /H /R";

System.Diagnostics.Process process = new System.Diagnostics.Process();

process.StartInfo.FileName = "cmd.exe";

process.StartInfo.Arguments = $"/c {command}";

process.StartInfo.RedirectStandardOutput = true;

process.StartInfo.UseShellExecute = false;

process.Start();

string output = process.StandardOutput.ReadToEnd();

process.WaitForExit();

Console.WriteLine(output);

}

}

```

方法四:使用Python的`shutil`模块