java 在 tomcat web 应用程序中打开一个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14627158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
open a file in a tomcat webapplication
提问by Maxiking1011
i want to open a file and return its content. Although it is in the same directory like the class that wants to open the file, the file can't be found. Would be cool if you could help me solving the problem.
我想打开一个文件并返回其内容。虽然和要打开文件的类在同一个目录下,但是找不到文件。如果你能帮我解决问题就好了。
Here is the code:
这是代码:
@GET @Produces("text/html") @Path("/{partNO}/") @Consumes("text/html")
public String getPartNoResponseHTML(@PathParam("partNO") String parID) throws WebApplicationException {
PartNoTemplate partNo = getPartNoResponse(parID);
String result = "";
try {
result = readFile(PART_NO_TEMPLATE_FILE);
} catch (FileNotFoundException e) {
e.printStackTrace(System.out);
return e.getMessage() + e.toString();
// throw new WebApplicationException(Response.Status.NOT_FOUND);
} finally {
result = result.replace("{partNO}", parID);
result = result.replace("{inputFormat}", partNo.getFormat().toString());
}
return result;
}
I guess it can't find the file, because its running on tomcat. I'm also using Jersey and JAX-RS. Thank you for your help,
我猜它找不到该文件,因为它在 tomcat 上运行。我也在使用 Jersey 和 JAX-RS。谢谢您的帮助,
Maxi
马克西
回答by ioan
If the file is inside the application WAR (or in a jar) you can try by using
如果文件在应用程序 WAR 中(或在 jar 中),您可以尝试使用
InputStream input = servletContext.getClass().getClassLoader().getResourceAsStream("my_filename.txt");
Your problem is similar (I think) with How can I read file from classes directory in my WAR?
您的问题类似于(我认为)与How can I read file from classes directory in my WAR?
回答by Paulius Matulionis
Try to get the path of the file from ServletContext.
尝试从ServletContext获取文件的路径。
ServletContext context = //Get the servlet context
In JAX-RS to get servlet context use this:
在 JAX-RS 中获取 servlet 上下文使用这个:
@javax.ws.rs.core.Context
ServletContext context;
Then get the file from your web application:
然后从您的 Web 应用程序获取文件:
File file = new File(context.getRealPath("/someFolder/myFile.txt"));
回答by Andres Olarte
You don't post the code that actually tries to read the file, but assuming the file is in the classpath (as you mention it's in the same directory as the class) then you can do:
您没有发布实际尝试读取文件的代码,但假设文件在类路径中(正如您所提到的,它与类位于同一目录中),那么您可以执行以下操作:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
See here
看这里