這是一個黑客位,但我認爲你需要像這樣:
@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:", ""));
}
}
什麼會'resource.replace( 「#」, 「%23」)'做? '#''只在URL中表示爲錨點,而不是URI。試試'「file:/ c:/ ...」'。 –
謝謝! Joop Eggen。它正在工作! – user3197661
哪一個?我的猜測'「文件:/ c:/ ...」' –