【问题标题】:Spring MVC file not found exceptionSpring MVC 文件未找到异常
【发布时间】:2016-12-03 09:38:11
【问题描述】:

我正在使用 Spring MVC。在我的控制器中,我从 MyClass 调用了一个函数

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

控制器:

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

当我在 MyClass 的 main() 中测试它时读取有效,但是当我在服务器上运行项目并访问“/url”时,我得到了这个:

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

如何在控制器中指定路径?

感谢您的宝贵时间。

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

服务器上的工作目录是什么?从那个目录,服务器上是否存在文件的相对路径(“myPath/myFile.txt”)?

假设您只需要阅读 myFile.txt,那么通常 myFile.txt 将包含在 WAR 中,并通过 getResourceAsStream 阅读。

【讨论】:

    【解决方案2】:

    我认为您正在寻找 Resource Spring 中的实现。 Spring 将确定要使用哪种类型的资源,例如,如果您的文件在类路径中,Spring 将创建一个ClasspathResource,或者它指向一个文件,它将创建一个FileResource。如果您使用的是 Spring 4。尝试类似

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

    看看这个Spring Resources docs

    【讨论】:

      【解决方案3】:

      因为这不是绝对路径。程序将在工作目录下查找文件 您可以将其添加到第一个程序和第二个程序中

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

      您会看到不同之处。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-28
        • 2022-01-18
        • 1970-01-01
        • 2019-03-29
        • 2019-06-26
        • 2012-01-06
        • 1970-01-01
        相关资源
        最近更新 更多