简体   繁体   English

如何在Java Web服务中查找文件路径

[英]How to find a files path within a java web-service

How can I find the path of my files that I have uploaded 如何找到已上传文件的路径

I am currently trying to return strings from text file through a restful web service. 我目前正在尝试通过一个宁静的Web服务从文本文件返回字符串。 However I am unable to access the file path location when running the web project on a tomcat server. 但是,在tomcat服务器上运行Web项目时,我无法访问文件路径位置。

The file is contained in 该文件包含在

Project root
|_Java Resources
  |_package
      |_MyServiceClass.java
|_ resources
   |_myText.txt

The service to be created is using javax and looks like 要创建的服务使用的是javax,看起来像

@GET
@Produces(MediaType.TEXT_HTML)
public String returnStriing() throws {
        String inputFileName  = "resources/myText.txt";
        File file = new File(inputFileName);
    }

The solution provided using relative path did not work for me. 使用相对路径提供的解决方案对我不起作用。 How do I find the path of the file? 如何找到文件的路径?

This is a common misunderstanding of resources. 这是对资源的普遍误解。 While they are "normal files" when you build your project, they will commonly be compiled into a JAR file or otherwise hidden away in a path location you cant access. 尽管它们在您构建项目时是“普通文件”,但通常会被编译成JAR文件,或者隐藏在您无法访问的路径位置。 If it's in a JAR, the File class will never be able to open it. 如果在JAR中,则File类将永远无法打开它。

Check out.. 查看..

this.getClass().getResourceAsStream("/myText.txt")

which will return an InputStream for the resource you are after. 它将为您所需要的资源返回一个InputStream。 note the / at the front. 注意前面的/。 it's an absolute path to the base of resources. 这是通往资源基础的绝对路径。

The reason this method is on Class, is that resources can exist in the same package as a class file. 此方法位于Class上的原因是,资源可以与class文件位于同一包中。 In this case you would use... 在这种情况下,您将使用...

this.getClass().getResourceAsStream("myText.txt")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM