当先锋百科网

首页 1 2 3 4 5 6 7

packagecom.lwq;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.OutputStream;importjava.io.PrintWriter;

public classResponse {private static final int BUFFER_SIZE = 1024;

Request request;

OutputStream output;publicResponse(OutputStream output){this.output =output;

}public void sendStaticResource() throwsIOException{byte[] bytes = new byte[BUFFER_SIZE];

FileInputStream fis= null;

File file= newFile(HttpServer.WEB_ROOT,request.getUri());if(file.exists()){try{

fis= newFileInputStream(file);int ch = fis.read(bytes,0,BUFFER_SIZE);while(ch != -1){

output.write(bytes,0,ch);

ch= fis.read(bytes,0,BUFFER_SIZE);

}

}catch(FileNotFoundException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}finally{if(fis !=null){

fis.close();

}

}

}else{//找不到文件

String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +

"Content-Type: text/html\r\n" +

"Content-Length: 23\r\n" +

"\r\n" +

"File Not Found";

try{

output.write(errorMessage.getBytes());

output.flush();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}publicRequest getRequest() {returnrequest;

}public voidsetRequest(Request request) {this.request =request;

}publicOutputStream getOutput() {returnoutput;

}public voidsetOutput(OutputStream output) {this.output =output;

}public static intgetBUFFER_SIZE() {returnBUFFER_SIZE;

}

}