Update download servlet to try-with-resources block. (#4453)
This commit is contained in:
parent
3b3008b6d5
commit
684324fc10
@ -4,7 +4,6 @@ import java.io.IOException;
|
|||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
|
|
||||||
import javax.servlet.ServletException;
|
|
||||||
import javax.servlet.annotation.WebServlet;
|
import javax.servlet.annotation.WebServlet;
|
||||||
import javax.servlet.http.HttpServlet;
|
import javax.servlet.http.HttpServlet;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
@ -15,21 +14,19 @@ public class DownloadServlet extends HttpServlet {
|
|||||||
private final int ARBITARY_SIZE = 1048;
|
private final int ARBITARY_SIZE = 1048;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
||||||
resp.setContentType("text/plain");
|
resp.setContentType("text/plain");
|
||||||
resp.setHeader("Content-disposition", "attachment; filename=sample.txt");
|
resp.setHeader("Content-disposition", "attachment; filename=sample.txt");
|
||||||
|
|
||||||
OutputStream out = resp.getOutputStream();
|
|
||||||
InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt");
|
|
||||||
|
|
||||||
byte[] buffer = new byte[ARBITARY_SIZE];
|
try (InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt");
|
||||||
|
OutputStream out = resp.getOutputStream()) {
|
||||||
int numBytesRead;
|
|
||||||
while ((numBytesRead = in.read(buffer)) > 0) {
|
byte[] buffer = new byte[ARBITARY_SIZE];
|
||||||
out.write(buffer, 0, numBytesRead);
|
|
||||||
|
int numBytesRead;
|
||||||
|
while ((numBytesRead = in.read(buffer)) > 0) {
|
||||||
|
out.write(buffer, 0, numBytesRead);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
in.close();
|
|
||||||
out.flush();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user