javaFx将文件拷贝到选择的路径
时间: 2023-08-08 14:08:54 浏览: 206
naosvu.rar_文件操作_Java_
你可以通过以下步骤在JavaFx中将文件复制到选择的路径:
1. 创建一个FileChooser对象来让用户选择需要拷贝的文件。
```java
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select File");
File selectedFile = fileChooser.showOpenDialog(stage);
```
2. 创建一个DirectoryChooser对象来让用户选择要拷贝文件的目标路径。
```java
DirectoryChooser dirChooser = new DirectoryChooser();
dirChooser.setTitle("Select Directory");
File destDir = dirChooser.showDialog(stage);
```
3.使用Java的IO类将文件从源文件夹复制到目标文件夹。
```java
if(selectedFile != null && destDir != null){
Path sourcePath = selectedFile.toPath();
Path destPath = Paths.get(destDir.getAbsolutePath(), selectedFile.getName());
Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
}
```
完整代码:
```java
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javafx.application.Application;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class FileCopy extends Application {
@Override
public void start(Stage stage) throws Exception {
// Create a FileChooser object to select the file to be copied
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select File");
File selectedFile = fileChooser.showOpenDialog(stage);
// Create a DirectoryChooser object to select the destination folder
DirectoryChooser dirChooser = new DirectoryChooser();
dirChooser.setTitle("Select Directory");
File destDir = dirChooser.showDialog(stage);
// Copy the selected file to the destination folder
if(selectedFile != null && destDir != null){
Path sourcePath = selectedFile.toPath();
Path destPath = Paths.get(destDir.getAbsolutePath(), selectedFile.getName());
Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
}
}
public static void main(String[] args) {
launch(args);
}
}
```
阅读全文