我有一个下载文件按钮,一旦点击将从网站下载文件并将其保存到通过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");
}
答案 0 :(得分:1)
使用FileChooser.showSaveDialog
的返回值代替initialDirectory
属性值:
File outputFile = saveAs.showSaveDialog(null);
if (outputFile != null) {
System.out.println("File name and location set");
saveFile(url, outputFile);
}