I'm working on a Java project developed in IntelliJ, and while it runs perfectly in the IDE, I want to learn how to compile and execute it directly from the Windows PowerShell. The project is organized across multiple package folders under the 'src' directory, including the 'Main' class, which contains the main method, located at srcmainMain.java.
I've attempted to compile it from the 'src' directory using the command `javac .mainMain.java`, but I didn't like how the .class files ended up being created in the same directory as the .java files. So, I tried using the command `javac -d out .mainMain.java` to direct the output to a different folder.
Despite trying various approaches, including setting the environment variable for the latest JDK, I faced issues running the program. A command I tried was `javac *.java`, which wasn't recognized by my system at all. I also attempted to use full path names in the javac command, without success.
Yesterday, I was able to compile the .class files into their respective packages in the 'out' folder, but when I tried to run it, I received the error: "Error: Could not find or load main class Main. Caused by: java.lang.NoClassDefFoundError: Main (wrong name: main/Main)."
The only way I've successfully run my program from the terminal is by executing the uncompiled file as `java mainMain.java`, which doesn't seem like the right approach. So, why can't I compile and run it properly, and why does this workaround even work?
3 Answers
Make sure you're using the `java` command to run the class file, not the .java file. It should be `java -cp out main.Main`, where 'out' is the folder you compiled into. This specifies the class path, so Java knows where to find your compiled classes. If you need more help with setting up the environment, feel free to ask!
Just a heads up, IntelliJ uses its own build system in the background, but you can switch to using build tools like Maven or Gradle which are also command-line based. These could help in managing builds and dependencies better if you decide to work from the terminal more often.
I see! That could be really useful. I'll need to look into it more.
You might want to try using `javac` with the correct package structure. For example, if your Main.java file is in the package 'main', you should navigate to the 'src' directory and run `javac main/Main.java`. This will also create the .class files in the appropriate package directory. Remember, Java requires the package structure to match the directory structure, so ensure everything is set up correctly.
Got it! I'll give that a shot, thanks!
Thanks, I'll definitely try that!