简体   繁体   中英

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. However I am unable to access the file path location when running the web project on a tomcat server.

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

@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. If it's in a JAR, the File class will never be able to open it.

Check out..

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

which will return an InputStream for the resource you are after. 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. In this case you would use...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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