1

How to save a file using FileChooser from JavaFX, here's my sample:

public static void clickDownloadButton(String filename,Stage window){
   File file = new File(filename);
   FileChooser fileChooser = new FileChooser();
   fileChooser.setTitle("Save file");
   fileChooser.showSaveDialog(window);
}
Vladlen Gladis
  • 1,699
  • 5
  • 19
  • 41
  • Possible duplicate of [Standard concise way to copy a file in Java?](http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java) BTW: sillyfly's answer already mentiones the IMHO best approach – fabian Jan 09 '16 at 18:10
  • The problem with the linked question is that IMHO the answers are overly-complicated (because they are outdated/before NIO was widely used? I don't know). using `Files.copy` is very simple, and I don't see a reason to mess around with streams or use external dependencies when it exists. – Itai Jan 10 '16 at 05:31

1 Answers1

5

Use java.nio.file.Files -

File dest = fileChooser.showSaveDialog(window);
if (dest != null) {
    try {
        Files.copy(file.toPath(), dest.toPath());
    } catch (IOException ex) {
        // handle exception...
    }
}
Itai
  • 6,641
  • 6
  • 27
  • 51
  • would you explain your code please? I don't understand what does this line do. `Files.copy(file.toPath(), dest.toPath());` in [docs.oracle](http://docs.oracle.com/javafx/2/ui_controls/file-chooser.htm) they have done in different way. – alhelal Sep 22 '17 at 13:27
  • See the [documentation](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.nio.file.Path-java.nio.file.Path-java.nio.file.CopyOption...-) for the method. It copies the file given by the first argument to the path given by the second argument. – Itai Sep 22 '17 at 13:45
  • from documentation "By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file" I want failure when the file exist, then which function should I use? – alhelal Sep 22 '17 at 14:35
  • If you want the operation **not** to succeed if the target already exists then just use this method. If you want to **replace** existing files use the `REPLACE_EXISTING` option, as described in the documentation. – Itai Sep 22 '17 at 14:49
  • "....just use this method..." which function? `Files.copy()`? But it always takes argument. – alhelal Sep 22 '17 at 16:42