问题描述
- Servlet类加载文件读取资源的问题
-
type Exception report message description The server encountered an internal error that prevented it from fulfilling this request. exception java.lang.NullPointerException com.itheima.Service.methdo2(Service.java:10) com.itheima.Demo8Servlet.doGet(Demo8Servlet.java:21) javax.servlet.http.HttpServlet.service(HttpServlet.java:617) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) note The full stack trace of the root cause is available in the Apache Tomcat/6.0.36 logs. 源码:package com.itheima; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Properties; public class Service { public void methdo2() throws FileNotFoundException,IOException{ Properties prop = new Properties(); prop.load(new FileReader(Service.class.getClassLoader().getResource("config.properties").getPath())); System.out.println(prop.getProperty("username")); System.out.println(prop.getProperty("password")); } } package com.itheima; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Demo8Servlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Service service = new Service(); service.methdo2(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
解决方案
问题出在prop.load(new FileReader(Service.class.getClassLoader().getResource("config.properties").getPath()));
应该是"config.properties“文件路径问题
时间: 2025-01-21 08:52:14