我正在阅读servlet编程。在实现ServletOutputStream以从相对路径读取图像时,它会抛出找不到文件的异常。
我尝试了多种方法但失败了,下面是eclipse中相关代码和文件夹结构的快照。
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
arg1.setContentType("image/jpeg");
ServletOutputStream out = arg1.getOutputStream();
FileInputStream fis = new FileInputStream("images/myimage.jpg");
BufferedInputStream bin = new BufferedInputStream(fis);
BufferedOutputStream boit = new BufferedOutputStream(out);
int ch = 0;
while((ch = bin.read() ) != -1){
boit.write(ch);
}
boit.close();
bin.close();
fis.close();
out.close();
}
}
答案 0 :(得分:0)
Get the ServletContext。然后是get the resource as a stream。
final InputStream imageStream = arg0.getServletContext().getResourceAsStream("/images/myiamge.jpg");