我需要下载文件.json
从我的应用程序中,但要选择其位置。
我知道如何将文件下载到磁盘,例如图像
<p:fileDownload value=""/>
public StreamedContent getFile(){ return new DefaultStreamedContent(stream, "image/jpg", "img.jpg"); }
我知道如何使用
GSON
写入文件给定路径try(JsonWrite j = new JsonWriter(new OutputStreamWriter( new FileOutputStream("C:\\...\\...\\file.json"), "UTF-8"))){ j.beginObject(); // ... j.name("foo"); gson.toJson(myObj, Foo.class, j); //... j.endObject(); }catch(...){...}
但我不知道如何将两者结合起来才能选择位置并在此位置写入 json ?
最佳答案
所以我认为你不能做你想做的事。您所能做的就是流式传输 JSON 文件并为其命名,例如“test.json”。出于安全原因,您不能告诉浏览器您希望用户下载的位置。我相信它与此请求类似:Browsing file system to select directory in JSF
但是,如果您只想发送 GSON 文件以允许用户下载它。
XHTML:
<p:fileDownload value="#{myController.downloadFile()}" />
JAVA:
public StreamedContent downloadFile() {
// convert GSON object to InputStream
String gson= json.getJSONObject("data").toString();
InputStream stream = new ByteArrayInputStream(gson.getBytes());
DefaultStreamedContent content = new DefaultStreamedContent(stream,
MediaType.APPLICATION_JSON,
"test.json");
return content;
}
关于java - 如何使用 GSON 从 Primeface 应用程序下载 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51417711/