是否可以通过路径访问jar内的资源?

时间:2014-07-23 17:11:29

标签: java jar soapui embedded-resource

我有一个运行在java项目中的SoapUI项目,该项目全部打包到jar中。该项目通过我的IDE运行良好unpackaged,但它通过命令行运行jar时遇到问题。以下是导致问题的代码:

SoapUITestCaseRunner runner = new SoapUITestCaseRunner();
ClassLoader cl = MyClass.class.getClassLoader();
runner.setProjectFile(cl.getResource("project.xml").getFile());
runner.run();

尝试从jar读取xml文件时,run方法出现问题。我是否可以从jar中获取可以输入setProjectFile方法的路径?我已经看到其他答案说要使用流,但此方法只接受字符串。

这是堆栈跟踪:

  

2014-07-23 12:03:58,384 ERROR [errorlog] com.eviware.soapui.support.SoapUIException:无法从文件加载项目[file:/ C:/temp/MyJar.jar!/project.xml ]   com.eviware.soapui.support.SoapUIException:无法从文件加载项目[file:/ C:/temp/MyJar.jar!/project.xml]     在com.eviware.soapui.impl.wsdl.WsdlProject.loadProject(WsdlProject.java:315)     在com.eviware.soapui.impl.wsdl.WsdlProject。(WsdlProject.java:231)     在com.eviware.soapui.impl.wsdl.WsdlProjectFactory.createNew(WsdlProjectFactory.java:41)     在com.eviware.soapui.impl.wsdl.WsdlProjectFactory.createNew(WsdlProjectFactory.java:28)     在com.eviware.soapui.tools.SoapUITestCaseRunner.runRunner(SoapUITestCaseRunner.java:329)     在com.eviware.soapui.tools.AbstractSoapUIRunner.run(AbstractSoapUIRunner.java:188)     在CommercialTests.ComTest.doTest(ComTest.java:14)     在CommercialTests.ServiceTests.main(ServiceTests.java:8)   引起:java.io.FileNotFoundException:C:\ temp \ MyJar.jar!\ project.xml(系统找不到指定的路径)     at java.io.FileInputStream.open(Native Method)     在java.io.FileInputStream。(未知来源)     在java.io.FileInputStream。(未知来源)     在sun.net.www.protocol.file.FileURLConnection.connect(未知来源)     at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)     在java.net.URL.openStream(未知来源)     在com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader.handleFile(UrlWsdlLoader.java:180)     在com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader.load(UrlWsdlLoader.java:116)     在com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader.load(UrlWsdlLoader.java:96)     在com.eviware.soapui.impl.wsdl.WsdlProject.loadProject(WsdlProject.java:297)     ......还有7个

1 个答案:

答案 0 :(得分:1)

对于像这样的事我通常会这样做:

URL res = getClass().getResource("/project.xml")    // is it at the root of your jar?!?!
File f = new File(res.getFile())
runner.setProjectFile(f.getCanonicalPath());

SoapUI,取决于它如何访问文件,可能需要在"真实"世界。以下是上述资源密集型版本。

// locate your file in the jar resources
URL res = getClass().getResource("/project.xml")    // is it at the root of your jar?!?!
// locate the resource in the filesystem
File f = new File(res.getFile())
// copy the file out into the real filesystem
File target = new File(System.getProperty("java.io.tmpdir") + File.separator + f.getName())
java.nio.file.Files.copy(f.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING)
runner.setProjectFile(target.getCanonicalPath())