另外,File
是指实际的OS文件系统文件;在操作系统的文件系统中,只有一个jar文件,该jar文件不是文件夹。您应该将URL的内容提取到临时文件,或者使用字节在内存中或作为流进行操作。
请注意,myURL.getFile()
返回字符串表示形式,而不是实际的File
。以类似的方式,这将不工作:
File f = new URL("http://www.example.com/docs/resource1.html").getFile();
f.exists(); // always false - will not be found in the local filesystem
一个很好的包装可能是以下几点:
public static File openResourceAsTempFile(ClassLoader loader, String resourceName)
throws IOException {
Path tmpPath = Files.createTempFile(null, null);
try (InputStream is = loader.getResourceAsStream(resourceName)) {
Files.copy(is, tmpPath, StandardCopyOption.REPLACE_EXISTING);
return tmpPath.toFile();
} catch (Exception e) {
if (Files.exists(tmpPath)) Files.delete(tmpPath);
throw new IOException("Could not create temp file '" + tmpPath
+ "' for resource '" + resourceName + "': " + e, e);
}
}
尝试移动“test.xsd”入类文件夹。如你所见,你调用getClassLoader()来搜索类路径中的文件。 –
你可以检查jar的内容,你的文件是否打包到jar中 –
IntelliJ可能已经添加了你的根文件夹作为类路径 –