【问题标题】:open a file in a tomcat webapplication在 tomcat Web 应用程序中打开文件
【发布时间】:2013-01-31 13:41:09
【问题描述】:

我想打开一个文件并返回它的内容。虽然和要打开文件的类在同一个目录下,但是找不到文件。如果您能帮我解决问题,那就太好了。

代码如下:

@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;
}

我猜它找不到该文件,因为它在 tomcat 上运行。我也在使用 Jersey 和 JAX-RS。感谢您的帮助,

马克西

【问题讨论】:

    标签: java file tomcat jersey


    【解决方案1】:

    如果文件在应用程序 WAR 中(或在 jar 中),您可以尝试使用

    InputStream input = servletContext.getClass().getClassLoader().getResourceAsStream("my_filename.txt");
    

    您的问题与How can I read file from classes directory in my WAR? 类似(我认为)

    【讨论】:

    • 我应该在哪里保存 txt 文件?
    【解决方案2】:

    尝试从ServletContext获取文件的路径。

    ServletContext context = //Get the servlet context
    

    在 JAX-RS 中获取 servlet 上下文使用这个:

    @javax.ws.rs.core.Context 
    ServletContext context;
    

    然后从您的网络应用程序中获取文件:

    File file = new File(context.getRealPath("/someFolder/myFile.txt"));
    

    【讨论】:

    • 非常感谢您对我的帮助! :)
    【解决方案3】:

    您不会发布实际尝试读取文件的代码,但假设文件位于类路径中(正如您提到的那样,它与类位于同一目录中),那么您可以这样做:

    InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
    

    here

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 2017-10-23
      • 2015-04-11
      • 1970-01-01
      • 2012-01-24
      • 2014-03-20
      • 2018-11-15
      • 1970-01-01
      • 2012-03-31
      相关资源
      最近更新 更多