使用Java实现功能:选择输入流和输出流,实现目录拷贝。注意目的地的文件名
时间: 2024-10-23 07:13:26 浏览: 30
在Java中,你可以使用`java.nio.file`包下的`Files`类来实现文件或目录的复制,这提供了强大的I/O操作能力。以下是一个简单的例子,它使用`copyTo()`方法从源目录复制到目标目录,并允许用户指定目标文件名:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DirectoryCopy {
public static void copyDirectory(String sourceDirPath, String destinationDirPath, String targetFileName) {
Path source = Paths.get(sourceDirPath);
Path destination = Paths.get(destinationDirPath + "/" + targetFileName);
try {
if (!Files.exists(destination)) { // 创建目标目录如果不存在
Files.createDirectories(destination.getParent());
}
Files.copy(source, destination); // 直接复制整个目录内容到指定文件
System.out.println("目录 " + sourceDirPath + " 已成功复制到 " + destination);
} catch (IOException e) {
System.err.println("复制目录时发生错误: " + e.getMessage());
}
}
public static void main(String[] args) {
String source = "/path/to/source/directory";
String destination = "/path/to/destination"; // 这里添加目标目录的完整路径
String fileName = "copied_directory_name"; // 用户可以输入的目标文件名
copyDirectory(source, destination, fileName);
}
}
```
在这个示例中,首先检查目标文件所在的目录是否存在,如果不存在则创建。然后使用`Files.copy()`方法将源目录的内容复制到目标文件。
阅读全文
相关推荐



















