0

I need to read in a file within a controller in Spring MVC app. What is the default location where I can put a file and then within my controller I can do the following:

@RequestMapping(value="/")
public ModelAndView test(HttpServletResponse response) throws IOException{  

        File file = new File("simple_file_name_without_any_path_information.txt");

            // reading in the file ....
}

Is there any additional configuration I need to do in order to make it work ? I tried putting the file under webapp\resources or webapp\WEB-INF or in plain webapp.

None of the options works.

Luke
  • 1,236
  • 2
  • 11
  • 16

1 Answers1

1

Using java.io.File, the default path will be the launch path, which in your case is probably the /bin folder of your application server (see In Java, what is the default location for newly created files?).

You might want to try Google Guava's Resources.getResource("your_file.txt") instead, which looks on the class path, and will find the file if it's in the resources folder. You can then also use Resources.readLines(url, Charsets.UTF_8) to read it.

What it does behind the scenes (in case you don't want to use a library) is basically:

ClassLoader loader = Objects.firstNonNull(
    Thread.currentThread().getContextClassLoader(),
    Resources.class.getClassLoader());
URL url = loader.getResource(resourceName);

You can then use the URL to create a File object.

Community
  • 1
  • 1
Andrei Fierbinteanu
  • 7,656
  • 3
  • 31
  • 45
  • Thanks, I used spring's ClasspathResource instead of guava's solution but the idea with putting files under src/resources works for me. – Luke May 23 '14 at 07:28