Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在tomcat Web应用程序中打开文件_Java_File_Tomcat_Jersey - Fatal编程技术网

Java 在tomcat Web应用程序中打开文件

Java 在tomcat Web应用程序中打开文件,java,file,tomcat,jersey,Java,File,Tomcat,Jersey,我想打开一个文件并返回其内容。虽然它与要打开该文件的类位于同一目录中,但找不到该文件。如果你能帮我解决这个问题就好了 代码如下: @GET @Produces("text/html") @Path("/{partNO}/") @Consumes("text/html") public String getPartNoResponseHTML(@PathParam("partNO") String parID) throws WebApplicationException { PartNoTemp

我想打开一个文件并返回其内容。虽然它与要打开该文件的类位于同一目录中,但找不到该文件。如果你能帮我解决这个问题就好了

代码如下:

@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。谢谢你的帮助


Maxi

您不会发布实际尝试读取文件的代码,但假设文件位于类路径中(如您所述,它与类位于同一目录中),则可以执行以下操作:

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

请参阅

如果文件位于应用程序WAR(或jar)中,您可以使用

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

您的问题(我认为)与

相似,请尝试从中获取文件的路径

在JAX-RS中,要获取servlet上下文,请使用以下命令:

@javax.ws.rs.core.Context 
ServletContext context;
然后从web应用程序获取文件:

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

非常感谢你对我的帮助!:)我应该把txt文件放在哪里?
File file = new File(context.getRealPath("/someFolder/myFile.txt"));