简体   繁体   中英

getClassLoader().getResource(“filename”).getFile() includes the JAR File Name in file path

I'm updating a system for additional requirements by the client. It is an old system which runs on java 1.4.2 and is compiled using maven and jdk 1.5.0_11.

One part of the system is loading of property file. The syntax used is:

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

I did not change anything on that code. However, when I deployed the jar file in Linux, it creates an incorrect file path. Currently, MyFile.txt is located inside the same folder as the compiled jar, and the code above from Old JAR get the correct file path. However, with the new compiled jar file, the generated file path of MyFile.txt included the name of the Jar in the file path. Please see below for more explanation.

Assuming that compiled Jar is CompiledJarv01.jar and is deployed in /Apps/myJar folder (MyFile.txt is inside also), the full file path of the MyFile.txt is

Old JAR File: /Apps/myJar/MyFile.txt

New JAR File: /Apps/myJar/CompiledJarv01.jar!/MyFile.txt

I am not sure why the Jar file name was included in MyFile.txt file path. This causes FileNotFoundException when running the application.

You could try something like:

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());

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM