[英]NoSuchFileException when running jar file
When I run a jar file that accesses other files in the src
directory, I get the following RuntimeException
: 当我运行访问
src
目录中其他文件的jar文件时,出现以下RuntimeException
:
Exception in thread "main" java.nio.file.NoSuchFileException: src\\FileToBeAccessed.txt.lck at sun.nio.fs.WindowsException.translateToIOException(Unknown Source) at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) at sun.nio.fs.WindowsFileSystemProvider.newFileChannel(Unknown Source) at java.nio.channels.FileChannel.open(Unknown Source) at java.nio.channels.FileChannel.open(Unknown Source) at java.util.logging.FileHandler.openFiles(Unknown Source) at java.util.logging.FileHandler.(Unknown Source) at Program.main(Program.java:30)
线程“主”中的异常java.nio.file.NoSuchFileException:src \\ FileToBeAccessed.txt.lck,位于sun.nio.fs.WindowsException.translateToIOException(未知源),位于sun.nio.fs.WindowsException.rethrowAsIOException(未知源) java.nio.channels.FileChannel.open上的sun.nio.fs.WindowsFileSystemProvider.newFileChannel(未知源)处的java.nio.channels.FileChannel处的sun.nio.fs.WindowsException.rethrowAsIOException(未知源)。 java.util.logging.FileHandler中的open(未知源).java.util.logging.FileHandler中的openFiles(未知源).Program.main(Program.java:30)中的(未知源)
The code works fine when I run it directly without building a jar file. 当我直接运行而不构建jar文件时,代码工作正常。
您需要更改将jar中的资源访问流的方式。
this.getClass().getResourceAsStream("/file.txt");
正确的方法是
this.getClass().getResourceAsStream("file.txt");
It is really strange that 真的很奇怪
this.getClass().getResource("file.txt")
does work in IDE but NOT when you run it from a jar. 可以在IDE中工作,但在jar中运行时却不能。
this.getClass().getResourceAsStream("file.txt")
works both inside IDE and from jar. 在IDE内部和jar中均可使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.