请用java提供将某个文件复制到指定文件夹(还未建好)的方法
时间: 2024-02-06 13:02:47 浏览: 25
你可以使用以下的Java代码来将文件复制到指定文件夹(如果该文件夹不存在,会自动创建):
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyExample {
public static void copyFileToDirectory(File sourceFile, File destinationDirectory) throws IOException {
// 创建目标文件夹(如果不存在)
if (!destinationDirectory.exists()) {
destinationDirectory.mkdirs();
}
// 创建目标文件
File destFile = new File(destinationDirectory, sourceFile.getName());
// 执行文件复制操作
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
}
System.out.println("文件复制完成!");
}
public static void main(String[] args) {
File sourceFile = new File("path/to/source/file.txt");
File destinationDirectory = new File("path/to/destination/directory");
try {
copyFileToDirectory(sourceFile, destinationDirectory);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请将 `"path/to/source/file.txt"` 替换为源文件的路径和名称,将 `"path/to/destination/directory"` 替换为目标文件夹的路径。这段代码会将源文件复制到指定的目标文件夹中。如果目标文件夹不存在,代码会自动创建它。