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循环里的代码写错了吗?

书上代码截图:
图片描述

阅读 4.3k
3 个回答

这里代码有问题,先检查这个吧
下面是我修改后的代码

//加上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);
}

这种问题我也很难解答,提供一个开发中的改BUG思路:
你问"是while循环里的代码写错了吗?"
你把这段代码全部删掉,你再重新看一下前台页面显示正常了吗,最终定位问题。
改bug难的在于定位问题,改是一小部分。
当然我觉得你的while循环写的是OK的 。

你这截图看起来是8080端口都没起来

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题