getClassLoader().getResource( "filename" ).getFile() 在文件路径中包含 JAR 文件名



我正在更新一个系统,以满足客户的额外需求。它是一个在java 1.4.2上运行的旧系统,使用maven和jdk 1.5.0_11进行编译。

系统的一部分是加载属性文件。使用的语法是:

String fileName = "MyClass".class.getClassLoader().getResource("MyFile.txt").getFile();
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(fileName);

我没有更改任何代码。但是,当我在Linux中部署jar文件时,它创建了一个不正确的文件路径。目前,MyFile.txt与编译后的jar位于同一个文件夹中,上面来自OldJAR的代码获得了正确的文件路径。但是,对于新编译的jar文件,生成的MyFile.txt文件路径在文件路径中包含了jar的名称。请参阅下文了解更多解释。

假设编译后的Jar是CompiledJarv01.Jar,并且部署在/Apps/myJar文件夹中(MyFile.txt也在里面),则MyFile.txt的完整文件路径是

旧JAR文件:/Apps/myJar/MyFile.txt

新的JAR文件:/Apps/myJar/CompiledJarv01.JAR/MyFile.txt

我不知道为什么Jar文件名包含在MyFile.txt文件路径中。这会在运行应用程序时导致FileNotFoundException。

您可以尝试以下操作:

File resource = new File("MyClass".class.getClassLoader().getResource("MyFile.txt").getFile());
String fileName = resource.getName();
File compiledJar = resource.getParentFile();
File newResource = new File(compiledJar.getParentFile(), filename);
System.out.println("The file you want (Hope so, I got no IDE): " + newResoruce.toString());

最新更新