Search code examples
javafxfileoutputstreamfilechooser

JavaFX FileChooser dir and file name passed to FileOutputStream


I have a download file button which once clicked will download a file from a website and save it to a location and name selected via FileChooser but I'm struggling to pass the file location and name to the FileOutputStream.

Does anybody have any suggestions please?

Thank you,

Paul

Here is my code:

public void GetFile()
{
    try
    {
        URL url = new URL("https://www.myURL.com/MyFile.xlsx");
        FileChooser saveAs = new FileChooser();
        saveAs.setInitialFileName("MyFile.xlsx");
        saveAs.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx"));
        saveAs.showSaveDialog(null);
        System.out.println("File name and location set");
        saveFile(url,saveAs.getInitialDirectory());
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}


public void saveFile(URL url, File saveAs) throws IOException {
    System.out.println("opening connection");
    InputStream in = url.openStream();
    FileOutputStream fos = new FileOutputStream(saveAs);
    System.out.println("Reading file...");
    int length = -1;
    byte[] buffer = new byte[1024];
    while ((length = in.read(buffer)) > -1) {
        fos.write(buffer, 0, length);
    }

    fos.close();
    in.close();
    System.out.println("File downloaded");
}

Solution

  • Use the return value of FileChooser.showSaveDialog instead of the initialDirectory property value:

    File outputFile = saveAs.showSaveDialog(null);
    
    if (outputFile != null) {
        System.out.println("File name and location set");
        saveFile(url, outputFile);
    }