Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

OutputStream already obtained  RSS feed

 
Lee Sha
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone tell me why do I get the Servlet exception - "OutputStream already obtained" for the below code?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ page import="com.aig.cruis.actionform.GenericExcelActionForm"%>
<%@ page import="com.aig.cafe.framework.util.IDataCapsule,com.aig.cruis.utils.AppValueFactory"%>
<%@ page import="com.aig.cafe.framework.util.FWConstants,com.aig.cruis.common.UserBean, java.io.*"%>

<%
IDataCapsule dc = (IDataCapsule)request.getAttribute("RequestDataCapsule");
GenericExcelActionForm form = (GenericExcelActionForm)dc.getObject(FWConstants.ACTION_FORM);

String fileName = form.getFileName();
File f = new File(fileName);

if (f.exists()) {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=" + form.getReportType() + ".xls");

FileInputStream fileInputStream = new FileInputStream(fileName);
OutputStream o = response.getOutputStream();

int i;
byte[] byteArr = new byte[256];
while ((i=fileInputStream.read(byteArr)) != -1) {
o.write(byteArr);
}

fileInputStream.close();
o.close();

File realFile = new File(fileName);
realFile.delete();
} else {
%>
Error Occurred...
<%
}
%>
 
Rob Spoor
Sheriff
Posts: 21087
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not too sure, but I think the DOCTYPE is causing the problem.

I haven't worked with JSP yet, but in PHP you can't set headers or cookies if there is even one single space outside any PHP block before it, since it has to be executed before anything is written. It wouldn't surprise me if JSP has the same limitation, but this time the getOutputStream() is causing the problems.
 
Lee Sha
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I debug, the exception is thrown when the control reaches realFile.delete();
 
Rob Spoor
Sheriff
Posts: 21087
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try not closing the output stream. While it is generally a good idea to do so, I don't think it isn't for JSP pages. What if that page, or another up the filter chain, still wants to write something? It won't be able to.
 
Lee Sha
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried by not closing the OutputStream. Still I get the exception.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!