저는 젊고 새로운 개발자이며 Java 서블릿으로 작업 한 적이 없습니다. .txt 파일을 다운로드 할 수있는 http URL이 있습니다 (예 : http://textfiles.com/100/914bbs.txt ).
그래서 저는 다른 포스트에서 본 것에 영감을 받아 Java 서블릿을 만들었습니다. 내 목표는이 .txt 파일을 다운로드하여 읽는 것입니다. 이 다운로드 한 파일을 "data.txt"에 저장하고 싶습니다.
ServletDownload 클래스 :
public class ServletDownload extends HttpServlet {
private static final int BYTES_DOWNLOAD = 1024;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/plain");
response.setHeader("Content-Disposition",
"attachment;filename=downloadname.txt");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("Donnees/data.txt");
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
}
이제 코드가 잘 작성되었는지, URL과 함께 사용하는 방법을 모르겠습니다 .
코드의 끝은 다음과 같을 수 있습니다 (스트림을 적절하게 닫는 try-with-resources 문 사용).
try (InputStream is = new URL("http://textfiles.com/100/914bbs.txt").openStream();
OutputStream os = response.getOutputStream()) {
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다