简体   繁体   English

如何在罐子外部读取XML文件?

[英]How do I read an XML file outside of a jar?

I'm trying to get the jar to read from target/classes outside of the jar so I can configure the data easier than going in the jar. 我正在尝试从jar之外的目标/类中读取jar,因此我可以比在jar中轻松配置数据。 The below is what I'm using to read the file, but it's reading from within the jar. 以下是我用来读取文件的内容,但它是从jar中读取的。 After reading the XML I'm using DocumentBuilder to parse the XML. 阅读XML之后,我使用DocumentBuilder解析XML。

ClassLoader classLoader = getClass().getClassLoader();
InputStream configFile = classLoader.getResourceAsStream(file);

The below is what I'm using to read the file, but it's reading from within the jar. 以下是我用来读取文件的内容,但它是从jar中读取的。

To read a resource outside the jar that you execute, don't use classloader to find the resource that will looks for in the running jar but use File or better Path that allows to locate/manipulate resources in a filesystem. 要在执行的jar之外读取资源,请不要使用classloader在正在运行的jar中查找要使用的资源,而应使用File或更好的Path来定位/处理文件系统中的资源。
You could just do it : 您可以这样做:

InputStream configFile =  Files.newInputStream(Paths.get(file));

Whatever, I am not sure that you use case be valid as reading a file from target/classes makes not really sense as resources located at this place are not designed to be persistent but to be packaged in the built artifact (here a JAR). 不管怎样,我不确定您的用例是否有效,因为从target/classes读取文件实际上没有意义,因为位于此位置的资源并非设计为持久性的,而是打包在构建的工件(此处为JAR)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM