[英]Reading from src/main/resources gives java.nio.file.InvalidPathException on command line (but works fine in Eclipse)
I read the file src\main\resources\input.txt as follows我读取文件 src\main\resources\input.txt 如下
String abslutefn = getClass().getClassLoader().getResource("input.txt").getFile().trim();
Path path = new File(abslutefn).toPath();
String lines = Files.readString(path);
Above works great from Eclipse.上面的作品从 Eclipse 开始。 But when I build and run from command line it fails
但是当我从命令行构建和运行时它失败了
mvn clean install
java -cp target\boolean.jar com.xx.yy.zz.App
Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 4: file:xyz
at java.base/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at java.base/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92)
at java.base/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:229)
at java.base/java.io.File.toPath(File.java:2290)
I peek into jar file我查看了 jar 文件
jar -tf target\boolean.jar
I see input.txt file at the root (and there is no src\main\resources)我在根目录下看到 input.txt 文件(并且没有 src\main\resources)
What can I do to ensure file loads correctly when I run from command line jar -tf target\stealthboolean.jar
.当我从命令行
jar -tf target\stealthboolean.jar
运行时,我该怎么做才能确保正确加载文件。 I am thinking something needs to be done in pom.xml but I am not sure what it is我想在 pom.xml 中需要做一些事情,但我不确定它是什么
You cannot use Path
and Files
with resources.您不能将
Path
和Files
与资源一起使用。
The getFile() method of URL does not return a valid file name. URL 的 getFile() 方法没有返回有效的文件名。 It's only called getFile() because java.net.URL was written 25 years ago, when URLs usually referred to physical files on other machines.
它之所以称为 getFile() 是因为 java.net.URL 是 25 年前编写的,当时 URL 通常指的是其他机器上的物理文件。
You can, however, open a resource as a stream, and convert the bytes yourself:但是,您可以将资源作为 stream 打开,然后自己转换字节:
String lines;
try (InputStream stream =
getClass().getClassLoader().getResourceAsStream("input.txt")) {
lines = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.