[英]Run an executable jar
I have a maven project in Eclipse.我在 Eclipse 中有一个 maven 项目。 Under the src/main/resources I have a directory named "directoryToCopy" containing files.
在 src/main/resources 下,我有一个名为“directoryToCopy”的目录,其中包含文件。 Once I run my project, I want to copy "directoryToCopy" under a local directory "localDirec" in my desktop.
一旦我运行我的项目,我想在我的桌面上的本地目录“localDirec”下复制“directoryToCopy”。
I used this:我用这个:
File localDirec = new File("c:/desktop/scripts");
URI urlDir = ClassLoader.getSystemResource("directoryToCopy").toURI();
File srcDir = new File(urlDir.getPath());
FileUtils.copyDirectory(srcDir, localDirec);
This works fine locally, but when I want to run it as an executable jar file I get NullPointerException这在本地工作正常,但是当我想将它作为可执行 jar 文件运行时,我得到 NullPointerException
Exception in thread "main" java.lang.NullPointerException
at java.base/java.io.File.<init>(File.java:278)
Any suggestion please?请问有什么建议吗?
You can always, try printing the path您可以随时尝试打印路径
System.out.println(getClass().getResource(getClass().getSimpleName() + ".class"));
Class's getResource()
- documentation states the difference:类的
getResource()
- 文档说明了区别:
"This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged ; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource." “此方法将调用委托给它的 class 加载器,在对资源名称进行这些更改后:如果资源名称以“/”开头,则它不变;否则,package 名称在转换“。”后附加到资源名称之前。到“/”。如果此 object 由引导加载程序加载,则调用委托给 ClassLoader.getSystemResource。
Use / when path should not be changed, try printing the loaded path, it would make things clear.当路径不应该改变时使用/ ,尝试打印加载的路径,它会让事情变得清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.