为什么在使用完整路径从文件系统读取文件时出现错误?
Why I am getting error when reading a file from file system using full path?
我有以下从文件系统读取文件的方法,我向方法提供了完整的文件名,包括“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() return 都是错误的。
这是 tomcat 日志中的错误显示:
cannot be resolved in the file system for checking its content length
另请注意,当我刷新页面时 (angular 9) 会显示文件(图片)
在屏幕上,所以这不是路径问题。
我已经搜索解决方案并找到了使用类路径的可能解决方案,但在我的情况下我不能使用它,因为要求是使用文件系统。该文件夹不能位于静态文件夹中,因为我不希望它位于 jar 文件中。在生产中,该文件夹应包含 140K 个文件,包括图片和视频。
我不喜欢这个解决方案,但它确实有效:
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 秒后中断,这没什么大不了的。
我有以下从文件系统读取文件的方法,我向方法提供了完整的文件名,包括“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() return 都是错误的。 这是 tomcat 日志中的错误显示:
cannot be resolved in the file system for checking its content length
另请注意,当我刷新页面时 (angular 9) 会显示文件(图片) 在屏幕上,所以这不是路径问题。 我已经搜索解决方案并找到了使用类路径的可能解决方案,但在我的情况下我不能使用它,因为要求是使用文件系统。该文件夹不能位于静态文件夹中,因为我不希望它位于 jar 文件中。在生产中,该文件夹应包含 140K 个文件,包括图片和视频。
我不喜欢这个解决方案,但它确实有效:
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 秒后中断,这没什么大不了的。