I have an executable JAR that has a file in it that i want to open as a java.io.File instance from code (not InputStream or anything else...just File).
Its a maven project and the file is at the root of "src/main/resources/file.xxx" The file is located at the root directory of the jar after packaging(verified that its there).
My first attempt: FileNotFoundException
java.io.File myFile = new java.io.File("file.xxx");
someMethodThatUsesTheFile(myFile); //I really need it to be a file!!!
Other attempts: FileNotFoundException
java.io.File myFile = new java.io.File("/file.xxx");
java.io.File myFile = new java.io.File("classpath:file.xxx");
java.io.File myFile = new java.io.File("classpath:/file.xxx");
I am not sure whats really going on. Web Apps can easily just load everything from the webapp root directory, Im confused as to why JAR apps behave differently.
Additional Info:
Short Answer: It is not a "File", so you just cant do it.
The JAR file is a File, but not its contents.
Alternatives would be:
Try other overloaded versions of that method, InputStreams are usually your options, you can load it using this code:
InputStream is = getClass().getResourceAsStream("file.xxx");
Move that file out of the JAR and into the same directory of the JAR (consider the security risks)
Try this one may help you :
URL url = this.getClass().getResource("src/main/resources/file.xxx");
File file= new File(url.toURI());
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.