this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
File file = new File(HttpServer.WEB_ROOT, request.getUri());
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
else {
// file not found
String errorMessage = "HTTP/1.1 404 File Not Found/r/n" +
"Content-Type: text/html/r/n" +
"Content-Length: 23/r/n" +
"/r/n" +
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
}
catch (Exception e) {
// thrown if cannot instantiate a File object
System.out.println(e.toString() );
}
finally {
if (fis!=null)
fis.close();
}
}
}
③发送请求的文件到web浏览器
package http;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class InputtoFilr {
public void saveinFile() {
try {
PrintStream ps = new PrintStream(new
FileOutputStream("D:\\test.txt"));
System.setOut(ps);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
四、 测试结果
打开web浏览器,在浏览器中输入请求的内容,观察运行的结果。
被请求的文件内容
五:实验总结
本次试验让我对Java web 服务器的实现有了更深入的了解,也了解了HTTP的GET请求字段的格式而且也能熟练的在机器上调试简单程序设计的思想,方法和调试。培养具有综合应用相关知识来解决测试问题的基础理论,培养在实践中研究问题,分析问题和解决问题的能力;还让我深深的感到了我们必须坚持理论联系实际的思想,以实践证实理论,从实践中加深对理论知识的理解和掌握。实验是我们快速认识和掌握理论知识的一条重要途径。