我正在尝试从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
将JAR文件从755最初更改为777。然后,我使用更改了权限chown
。但是它仍然没有用。我不是Unix专家,所以我不能对此做很多深入研究。好心提醒!谢谢!
正如我在上面的评论中所说,问题是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;
这对我有用。