我从Eclipse获得了以下用于Java应用程序的文件结构,我使用Apache Commons Daemon将其转换为Windows服务。
SubscriberACD
/Maven Dependencies
/src/main/java
/org.SubscriberACD
/Subscriber.java
/src/test/java
/JRE System Librar
/src
/target
config.xml
pom.xml
在Subscriber.java中,这里是定义字符串的地方:
private static final String CONFIG_FILE = "config.xml";
以下是从xml文件中读取的代码段(基于以下帖子:Java: How to read and write xml files?):
Document document;
DocumentBuilderFactory doc_builder_factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder doc_builder = doc_builder_factory.newDocumentBuilder();
document = doc_builder.parse(CONFIG_FILE);
我的服务文件目录如下所示:
E:\SubscriberACD
\bin
\subscriberACD.exe
\subscriberACDw.exe
\classes
\org
\SubscriberACD
\Subscriber.class
\config.xml
\3rdpartyjarfiles
\SubscriberACD.jar
\logs
请注意我是如何在类下的SubscriberACD下粘贴config.xml来试试的。但它没有用。另外值得注意的是,我还将我的项目导出为SubscriberACD.jar并将其放在\ classes文件夹下。从eclipse开始,看起来config.xml也被打包在那个jar中。当我尝试启动Windows服务时出现以下错误:
2016-04-16 15:08:27 Commons Daemon procrun stderr initialized
Exception in thread "main" n\config.xml (The system cannot find the file specified)
java.lang.NumberFormatException: For input string: "null"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at zmq.TcpAddress.resolve(TcpAddress.java:105)
at zmq.Address.resolve(Address.java:98)
at zmq.SocketBase.connect(SocketBase.java:510)
at org.zeromq.ZMQ$Socket.connect(ZMQ.java:1246)
at org.SubscriberACD.Subscriber.start(Subscriber.java:114)
at org.SubscriberACD.Subscriber.windowsService(Subscriber.java:61)
我错过了一些额外的配置吗?
答案 0 :(得分:1)
试试这个: 将文件config.xml直接放入classes文件夹:
E:\SubscriberACD\classes\config.xml
然后在Subscriber.java中尝试加载这样的文件:
Document document;
DocumentBuilderFactory doc_builder_factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder doc_builder = doc_builder_factory.newDocumentBuilder();
try(InputStream instream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.xml")) {
document = doc_builder.parse(instream);
}
} catch(SAXException | ParserConfigurationException e) {
throw new RuntimeException(e);
}
答案 1 :(得分:0)
(Eclipse)创建一个源文件夹并将“config.xml”粘贴到其中。
InputStream is = getClass().getClassLoader().getResourceAsStream("config.xml");
使用进行解析是(InputStream)