java server throws java.lang.IllegalStateException: Cannot call sendError() after the response has been committed

StackOverflow https://stackoverflow.com//questions/22008304

  •  21-12-2019
  •  | 
  •  

質問

please help me java server throws : java.lang.IllegalStateException: Cannot call sendError() after the response has been committed I rechecked many times and googled alot but i cant find what's the problem here's my code

    DataOutputStream stream = null;
BufferedInputStream buf = null;
try {
response = ServletActionContext.getResponse();
response.setHeader(Constants.AU_TRST_X_RESULT_CD, "0"); // x-resultCd = 0 is OK
// add RSP_KEY_CODE to header
response.setHeader(Constants.RSP_KEY_CODE, Constants.RSP_SUCCCESS + "");
response.setContentType("application/csv");
//------------ write csv file to body ----------
// get response's outputStream
stream = new DataOutputStream(response.getOutputStream());
// fix file csv
File csvFixFile = new File("E:\\a.xls");   
// buffer to read csv File

File csvResponse = new File(csvFixFile.getPath());
// file Input to read csv File
FileInputStream inputStream = new FileInputStream(csvResponse);
buf = new BufferedInputStream(inputStream);
int readBytes = 0;
while ((readBytes = buf.read()) != -1) {
stream.write(readBytes);
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != buf)
try {buf.close();} catch (Exception e2) {e2.printStackTrace();}
if (null != stream)
try {stream.close();} catch (Exception e2) {e2.printStackTrace();}  
}

.It looks okay but it didnt work properly and perhaps the problem is in the while loop please point it out for me.....

役に立ちましたか?

解決

You can use IOUtils from apache commons-io to copy input stream into output stream (it also uses buffer, so you don't need to):

ServletOutputStream outStream = response.getOutputStream();
IOUtils.copy(inputStream, outStream);

IOUtils javadoc

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top