[OmniFaces utilities] The
getResourceAsStream()
method returns an input stream for an application resource mapped to the specified path, if it exists; otherwise, return null
.Method:
See also: Faces#getContext()
Usage:
For example,
when you download a file, you can use Faces#getResourceAsStream(), as
below:
public void
readFileAction() throws IOException, URISyntaxException {
FacesContext facesContext =
FacesContext.getCurrentInstance();
ExternalContext externalContext =
facesContext.getExternalContext();
Path path =
Paths.get(externalContext.getRealPath("/resources/rafa.txt"));
BasicFileAttributes attrs =
Files.readAttributes(path, BasicFileAttributes.class);
externalContext.responseReset();
externalContext.setResponseContentType("text/plain");
externalContext.setResponseContentLength((int)
attrs.size());
externalContext.setResponseHeader("Content-Disposition",
"attachment; filename=\"" + "rafa.txt" +
"\"");
int nRead;
byte[] data = new byte[128];
InputStream inStream = Faces.getResourceAsStream("/resources/rafa.txt");
try (OutputStream output =
externalContext.getResponseOutputStream()) {
while ((nRead = inStream.read(data, 0,
data.length)) != -1) {
output.write(data, 0, nRead);
}
output.flush();
}
facesContext.responseComplete();
}
Niciun comentariu :
Trimiteți un comentariu