0

I'm using Spring MVC. In my controller I called a function from MyClass

MyClass{
  public static void readFile(){
    File file = new FileReader("myPath/myFile.txt");
    ...
  }
  public static void main(String[] args) {
    readFile();//No problem
  }
}

controller:

@Controller
public class MyController{
  @RequestMapping(value = "/url", method = RequestMethod.GET)
  public String readFile(Locale locale, Model model) {
    MyClass.readFile();//File not found exception
    ....
  }
}

The reading works when I test it in the main() of MyClass, but when I run the project on server and visit "/url", I got this:

java.io.FileNotFoundException: myPath/myFile.txt (The system cannot find the path specified)

How do I specify the path in the controller?

Thank you for your time.

Daolin
  • 614
  • 1
  • 16
  • 41
  • 1
    Maybe this could be useful to you https://stackoverflow.com/questions/36371748/spring-boot-access-static-resources-missing-scr-main-resources – lenach87 Jul 28 '16 at 20:10

3 Answers3

0

What is the working directory on the server? From that directory, does the relative path to the file ("myPath/myFile.txt") exist on the server?

Assuming you only need to read myFile.txt, then typically myFile.txt would be included within the WAR, and read via getResourceAsStream.

Community
  • 1
  • 1
Andrew S
  • 2,509
  • 1
  • 12
  • 14
0

I think you are looking for Resource implementations in Spring. Spring will determine which type of Resource to use, for example if your file is in the classpath Spring will create a ClasspathResource or it points to a file it will create a FileResource. If you are using Spring 4. Try something like

@Value("file:///myPath/myFile.txt")
Resource myFile;

Have a look at this Spring Resources docs

Laksitha Ranasingha
  • 4,321
  • 1
  • 28
  • 33
0

because this is not absolutely path. Program will find files under Working Directory you can add this into first program and the second one

   System.out.println("Working Directory = " +
    System.getProperty("user.dir"));

You will see the difference.

unhappy
  • 26
  • 2