Hopefully this will make some sense. I'm new to Java and while I've built .jar artifacts before, I have never had to build a program that takes another file as input. I'm running into a weird problem and I'm not sure how to fix it.
Basically, I have a Main.java class that calls a .txt file and passes it to another class, myClass.java. I generated a .jar file with IntelliJ, which inserted itself inside its own folder.
To make things easier, here is the basic structure of my program.
/src
/com.myProgram
Main.java
input.txt
MyClass.java
/out
/artifacts
/myProgram_jar
myProgram.jar
And here is a basic version of what's in Main.java
myClass mc = new myClass("input.txt");
I tried running the .jar file with the command "java -jar myProgram.jar", and I get the error "The system cannot find the path specified". I ran getCanonicalPath() on input.txt. Apparently my program is looking for input.txt in out/artifacts/myProgram_jar instead of in the src/ folder.
What can I do? Even when I put the full path to force the program to look in the src/ folder, it will still attempt to look in the myProgram_jar folder and throw an error. So I cannot execute the file at all. Any suggestions for solving this error are greatly appreciated!
When you build to jar file, it's not a File anymore. A File is only a physical file on the file ystem.
So have 2 way to fix it:
1. You export the txt file to system as D:/New folder, then you get this file with path of this file.
2. You can try this:
try {
URL url = new URL(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().toString()+your path to file in structre);
InputStream in = url.openStream();
} catch (URISyntaxException ex) {
Logger.getLogger(PrepareGUI.class.getName()).log(Level.SEVERE, null, ex);
}
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.