gpt4 book ai didi

java - servlet中的文件读取问题

转载 作者:行者123 更新时间:2023-11-29 03:51:22 25 4
gpt4 key购买 nike

我必须使用 servlet 读取文件。这是我正在使用的代码。但文件未使用此代码读取。始终打印 File contains null value-------------- ----:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("text/html");
String filename = "D/root.properties";
ServletContext context = getServletContext();

InputStream inp = context.getResourceAsStream(filename);
if (inp != null) {
InputStreamReader isr = new InputStreamReader(inp);
BufferedReader reader = new BufferedReader(isr);
PrintWriter pw = response.getWriter();

String text = "";

while ((text = reader.readLine()) != null) {
}
} else {
System.out.println("File contains null value-----------------");
}
} catch(Exception e) {
System.out.println("Rxpn............................................."+e);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}

最佳答案

javadoc救援:

java.net.URL getResource(java.lang.String path) throws java.net.MalformedURLException

Returns a URL to the resource that is mapped to the given path.

The path must begin with a / and is interpreted as relative to the current context root, or relative to the /META-INF/resources directory of a JAR file inside the web application's /WEB-INF/lib directory. This method will first search the document root of the web application for the requested resource, before searching any of the JAR files inside /WEB-INF/lib. The order in which the JAR files inside /WEB-INF/lib are searched is undefined.

如果您想从 Web 应用程序中读取资源,请使用上述路径。如果你想从文件系统读取,使用文件 IO(和正确的文件名):new FileInputStream("D:/root.properties")

关于java - servlet中的文件读取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8654193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com