从JAR读取文件(NoSuchFileException)

问题描述 投票:-1回答:1

我正在尝试从JAR文件中读取一些文件。 JAR文件位于Tomcat的lib文件夹中。我正在读取文件,例如:

String filePath = DirectoryReader.class.getClassLoader().getResource(directoryPath).getPath();

System.out.println("Directory Path: " + directoryPath);
System.out.println("File Path 1: " + filePath);

filePath = filePath.substring(6, filePath.indexOf("!"));

System.out.println("File Path 2: " + filePath);

Path configJARLocation = Paths.get(filePath);
System.out.println("JAR location: " + configJARLocation.toString());
InputStream inputStream = Files.newInputStream(configJARLocation);
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
InputStreamReader inputStreamReader = null;

但是我在日志中得到了例外:

Directory Path: META-INF/gmm/xmlFiles/predefined/ipsec/
File Path 1: file:/opt/app/tools/tomcat/lib/appConfigurations.jar!/META-INF/gmm/xmlFiles/predefined/ipsec/
File Path 2: opt/app/tools/tomcat/lib/appConfigurations.jar
JAR location: opt/app/tools/tomcat/lib/appConfigurations.jar
java.nio.file.NoSuchFileException: opt/app/tools/tomcat/lib/appConfigurations.jar
        at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
        at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
        at java.nio.file.Files.newByteChannel(Files.java:361)
        at java.nio.file.Files.newByteChannel(Files.java:407)
        at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
        at java.nio.file.Files.newInputStream(Files.java:152)
        at com.gtc.logicalprovisioning.dac.file.DirectoryReader.process(DirectoryReader.java:72)

除了/前面的opt前,我看不到任何不正确的内容。代码的第72行是:

InputStream inputStream = Files.newInputStream(configJARLocation);

相同的代码在Windows中工作。仅当我在Unix环境中进行部署时,它才会开始失败。我最初以为是许可或访问问题。但似乎并非如此。我先将chmod从755更改为JAR文件的777。然后,我使用chown更改了权限。但是它仍然没有用。我不是Unix专家,所以我不能对此做很多深入研究。好心提醒!谢谢!

java unix nio
1个回答
0
投票

正如我在上面的评论中所说。问题是file:/前缀。由于我正在进行字符串操作,因此起始索引为6,这导致第一个/从Unix路径中被剪切掉。

Windows路径类似于:

file:/H:/...

无法真正说出为什么Windows路径前面加了一个/。如果有人可以启发我,那就太好了。

Unix路径类似于:

file:/opt/...

因此,更干净的选择是使用URL / URI API来完成它。应该早点想到这一点,因为这是解决该问题的一种更优美的方法。

// JAR File Reading
String filePath = DirectoryReader.class.getClassLoader().getResource(directoryPath).getPath();

filePath = filePath.substring(0, filePath.indexOf("!"));

URL url = new URL(filePath);

Path configJARLocation = Paths.get(url.toURI());

InputStream inputStream = Files.newInputStream(configJARLocation);
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
InputStreamReader inputStreamReader = null;

这对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.