当文件名包含“#”时,我发现错误。
错误:java.lang.IllegalStateException:文件不存在。
但是当没有“#”的文件名仍在工作时。
String resource = "file:c:/Test#.txt";
PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
Resource[] resolveResources;
try {
resolveResources = pathResolver.getResources(resources);
if(resolveResources.length == 0) {
throw new IllegalStateException("File does not exist: " + resources);
}else{
for (Resource resource : resolveResources) {
if(!resource.exists()){ //true
throw new IllegalStateException("File does not exist: " + resource);
}
}
}
} catch (IOException e) {
throw new IllegalStateException("File does not exist: " + resources);
}
答案 0 :(得分:1)
文件名有效性取决于操作系统(文件系统更准确),因此要确保可以在任何操作系统上读取该文件;使用字母数字和下划线Characters to avoid
在您的程序中,问题出在URI制作函数
"subscriptions.entity_type"
答案 1 :(得分:0)
这有点像黑客,但我认为你需要这样的东西:
@Test
public void test1() {
try {
String resource = "file:c:\\tmp\\Test\u0023.txt";
PathMatchingResourcePatternResolver pathResolver = new TestPathMatchingResourcePatternResolver();
Resource[] resolveResources;
resolveResources = pathResolver.getResources(resource);
if (resolveResources.length == 0) {
throw new IllegalStateException("File does not exist: " + resource);
} else {
for (Resource resource2 : resolveResources) {
if (!resource2.exists()) { // true
throw new IllegalStateException("File does not exist: " + resource2);
}
}
}
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
然后你需要添加修改PathMatchingResourcePatternResolver
public class TestPathMatchingResourcePatternResolver extends PathMatchingResourcePatternResolver {
public TestPathMatchingResourcePatternResolver() {
super(new TestDefaultResourceLoader());
}
}
然后你需要修改DefaultResourceLoader
public class TestDefaultResourceLoader extends DefaultResourceLoader {
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
if (location.startsWith("/")) {
return getResourceByPath(location);
} else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
} else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return new TestUrlResource(url);
} catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}
}
然后你需要修改UrlResource
public class TestUrlResource extends UrlResource {
public TestUrlResource(URL url) {
super(url);
}
@Override
public boolean exists() {
return true;
}
@Override
public File getFile() throws IOException {
return new File(getURL().toString().replace("file:", ""));
}
}