【问题标题】:Copy selected file to Project directory将选定的文件复制到项目目录
【发布时间】:2016-08-20 14:12:42
【问题描述】:
我是 JavaFx 的新手,我想知道如何将 Filechooser 选择的文件复制到我的项目文件夹中。
public void ButtonAction(ActionEvent event) {
FileChooser fc = new FileChooser();
fc.setTitle("attach a file");
File selectedFile = fc.showOpenDialog(null);
if (selectedFile != null) {
file1.setText("selectionned file : " + selectedFile.getAbsolutePath());
//the code to copy the selected file goes here//
} else{
file1.setText("no file attached");
}
【问题讨论】:
标签:
java
javafx
filechooser
file-copying
【解决方案1】:
您可以使用Files 类来复制文件,例如:
Files.copy(selectedFile.toPath, targetDirPath);
【解决方案2】:
无论如何,问题已解决。
Path from = Paths.get(selectedFile.toURI());
Path to = Paths.get("pathdest\\file.exe");
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(from, to, options);
【解决方案3】:
为了让任何想要复制此方法的实际代码并在上面的代码中遇到一些麻烦的人更容易(因为其中一些根本不起作用):
private Path to;
private Path from;
private File selectedFile;
private void handleFileLocationSearcher() throws IOException {
FileChooser fc = new FileChooser();
fc.setTitle("Attach a file");
selectedFile = fc.showOpenDialog(null);
if (selectedFile != null) {
from = Paths.get(selectedFile.toURI());
to = Paths.get("Your destination path" + selectedFile.getName());
Files.copy(from.toFile(), to.toFile());
}
}
您可以使用selectedFile.toString() 或selectedFile.getName() 将其添加到文本字段中,或者通常只获取您尝试通过文件选择器检索的文件的路径或名称。
如果您希望在另一个按钮按下时发生Files.copy(from.toFile(), to.toFile());,您也可以在应用程序的其他地方使用它,因为变量可以在类中的任何地方使用。如果您不需要这样做,只需在方法中创建局部变量即可。
【解决方案4】:
Applemelon 的解决方案只是我没有调用 toFile() 方法
Files.copy(from.toFile(), to.toFile()); 给出了一个无法解析方法错误,而Files.copy(from, to) 为我工作。
private Path to;
private Path from;
private File selectedFile;
private void handleFileLocationSearcher() throws IOException {
FileChooser fc = new FileChooser();
fc.setTitle("Attach a file");
selectedFile = fc.showOpenDialog(null);
if (selectedFile != null) {
from = Paths.get(selectedFile.toURI());
to = Paths.get("Your destination path" + selectedFile.getName());
// Files.copy(from.toFile(), to.toFile()); //gives a 'cannot resolve method error
Files.copy(from, to);
}
}