有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么在使用完整路径从文件系统读取文件时出错?

为了从文件系统中读取文件,我向方法提供了完整的文件名,包括“c://”。方法如下:

private Resource loadAsResource(String filename) throws MalformedURLException {     
              Path file = root.resolve(filename);
              Resource resource = new UrlResource(file.toUri());
                         
              if (resource.exists() || resource.isReadable()) {
                return resource;
              }
            return null;                        
    }

打印日志时,我发现exist()和isReadable()都返回false。 以下是tomcat日志中显示的错误:

cannot be resolved in the file system for checking its content length

还请注意,当我刷新页面(第9页)时,会显示文件(图片) 所以这不是路径问题。 我已经搜索了解决方案并找到了使用类路径的可能解决方案,但在我的情况下,我不能使用它,因为要求使用文件系统。该文件夹不能位于静态文件夹中,因为我不希望它位于jar文件中。在制作中,文件夹应包含140K个文件,包括图片和视频


共 (1) 个答案

  1. # 1 楼答案

    我不喜欢这个解决方案,但它很有效:

    private Resource loadAsResource(String filename) {
            try {
                  Path file = root.resolve(filename);
                  Resource resource = new UrlResource(file.toUri());
                  int i=0;
                  while(!resource.exists() || !resource.isReadable()) {
                      Thread.sleep(100);
                      if (++i == 20) {
                          break;
                      }
                  }
                  return resource;                    
                } catch (MalformedURLException e) {
                  throw new RuntimeException("Error: " + e.getMessage());
                } catch (InterruptedException e) {
                     throw new RuntimeException("Could not read the file!");
                }       
        }
    

    2秒后循环将被打破,这没什么大不了的