You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NanoHTTPD调用getResourceAsStream返回null读取资源失败求助

问题根因

  1. Class.getResourceAsStream入参误用:该API仅支持读取类路径下的资源,不识别操作系统的绝对文件路径,你传入的/Users/xxx/...本地路径会被类加载器判定为不存在,返回null,调用readAllBytes()时触发空指针。
  2. 字节转字符串逻辑错误:直接调用byte[].toString()会输出字节数组的对象标识,而非文件文本内容。
  3. 缺少静态资源路由:当前代码仅处理了/和/login路径,后续login.html加载关联的loginhandler.js时请求会无响应。

修复方案

1. 修改资源读取方法

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

private String readFileAsTextUsingInputStream(String resourcePath) throws IOException {
    // 入参为类路径下的资源路径,示例:/html/login.html、/js/loginhandler.js
    try (InputStream inputStream = Connection.class.getResourceAsStream(resourcePath)) {
        if (inputStream == null) {
            throw new FileNotFoundException("未找到资源:" + resourcePath);
        }
        byte[] fileBytes = inputStream.readAllBytes();
        // 指定编码转换为字符串,避免乱码
        return new String(fileBytes, StandardCharsets.UTF_8);
    }
}

2. 优化serve路由逻辑

@Override
public Response serve(IHTTPSession session) {
    String uri = session.getUri();
    try {
        // 登录页路由
        if ("/login".equals(uri)) {
            String htmlContent = readFileAsTextUsingInputStream("/html/login.html");
            return newFixedLengthResponse(Response.Status.OK, "text/html", htmlContent);
        }
        // 静态资源路由(js、css等)
        else if (uri.startsWith("/js/") || uri.startsWith("/css/")) {
            String content = readFileAsTextUsingInputStream(uri);
            return newFixedLengthResponse(Response.Status.OK, getMimeType(uri), content);
        }
        // 首页路由
        else if (uri.isBlank() || "/".equals(uri)) {
            String msg = "<html><body><h1>Die Website finden Sie<a href=http://"+this.getHostname()+":"+
                    this.getListeningPort()+"/login>hier</a></h1></body></html>".trim();
            return newFixedLengthResponse(Response.Status.OK, "text/html", msg);
        }
        // 兜底404响应
        return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "请求资源不存在");
    } catch (IOException e) {
        e.printStackTrace();
        return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, "text/plain", "服务器内部错误");
    }
}

额外校验项

  • 确认构建工具(Maven/Gradle)已将src/main/resources标记为资源目录,编译后target/classes目录下能看到html、js文件夹及对应文件
  • IDE运行时需确认resources文件夹被标记为资源根目录:IDEA中右键resources文件夹 → Mark Directory as → Resources Root

内容的提问来源于stack exchange,提问作者Erwin109

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 09:54:04