传递给 FileOutputStream 的 JavaFX FileChooser 目录和文件名

JavaFX FileChooser dir and file name passed to FileOutputStream

我有一个下载文件按钮,单击该按钮将从网站下载文件并将其保存到通过 FileChooser 选择的位置和名称,但我正在努力将文件位置和名称传递给 FileOutputStream。

大家有什么建议吗?

谢谢,

保罗

这是我的代码:

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");
}

使用 FileChooser.showSaveDialog 的 return 值代替 initialDirectory 属性 值:

File outputFile = saveAs.showSaveDialog(null);

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