java - OutputStream的write方法没写html到页面
本文介绍了java - OutputStream的write方法没写html到页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
File file = new File(HttpServer.WEB_ROOT, request.getUri());
try {
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, 1024);
while (ch != -1) {
outputStream.write(bytes, 0, ch);
ch = fis.read(bytes, 0, 1024);
}
} 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" + "<h1>File Not Found</h1>";
outputStream.write(errorMessage.getBytes());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null)
fis.close();
}
我的项目webroot下有index.html 我访问http://localhost:8080/index.html 代码执行了while循环里的代码,但是前台显示是while循环里的代码写错了吗?
书上代码截图:
解决方案
这里代码有问题,先检查这个吧
下面是我修改后的代码
//加上http响应头
String responseHead = "HTTP/1.1 200 ok\r\nContent-Type: text/html\r\nContent-Length: "+file.length()+"\r\n\r\n";
outputStream.write(responseHead.getBytes());
int ch = -1;
while ((ch =fis.read(bytes)) != -1) {
outputStream.write(bytes, 0, ch);
}
这篇关于java - OutputStream的write方法没写html到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文