NanoHTTPD调用getResourceAsStream返回null读取资源失败求助
问题根因
Class.getResourceAsStream入参误用:该API仅支持读取类路径下的资源,不识别操作系统的绝对文件路径,你传入的/Users/xxx/...本地路径会被类加载器判定为不存在,返回null,调用readAllBytes()时触发空指针。- 字节转字符串逻辑错误:直接调用
byte[].toString()会输出字节数组的对象标识,而非文件文本内容。 - 缺少静态资源路由:当前代码仅处理了
/和/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
相关产品推荐
相关产品推荐

