另外,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可能已經添加了你的根文件夾作爲類路徑 –