I read the file src\main\resources\input.txt as follows
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. 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 -tf target\boolean.jar
I see input.txt file at the root (and there is no src\main\resources)
What can I do to ensure file loads correctly when I run from command line jar -tf target\stealthboolean.jar
. I am thinking something needs to be done in pom.xml but I am not sure what it is
You cannot use Path
and Files
with resources.
The getFile() method of URL does not return a valid file name. It's only called getFile() because java.net.URL was written 25 years ago, when URLs usually referred to physical files on other machines.
You can, however, open a resource as a stream, and convert the bytes yourself:
String lines;
try (InputStream stream =
getClass().getClassLoader().getResourceAsStream("input.txt")) {
lines = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.