Skip to content

Instantly share code, notes, and snippets.

@claraj
Last active July 30, 2024 07:16
Show Gist options
  • Save claraj/bc6ad412d724d7f910fabd01816e86f5 to your computer and use it in GitHub Desktop.
Save claraj/bc6ad412d724d7f910fabd01816e86f5 to your computer and use it in GitHub Desktop.
Running Java code from the command line

Plain Java Project (not Maven, no GUI, no dependencies)

Assuming files are in /src/com/clara/ and main method is in Main.java

compile with javac src/com/clara/*.java or for Windows users java src\com\clara\*.java

execute with java -cp ./src com.clara.Main or for Windows users java -cp src com.clara.Main

The -cp flag sets the classpath, in effect, telling Java where to look for the code that makes up your project. More info: http://kevinboone.net/classpath.html/

Manually managed dependencies (No Maven)

Assuming files are in /src/com/clara/ and main method is in Main.java

Create a directory for dependencies in your project. A common name for this directory is lib/. Download dependencies JAR files from (e.g.) Maven Central https://search.maven.org/ and put them in the lib/ directory

compile code with javac -cp "lib/*" src/com/clara/*.java or for Windows users javac -cp "lib\*" src\com\clara\*.java

run code with java -cp "lib/*:src" com.clara.Main or for Windows users java -cp "lib\*;src" com.clara.Main

Maven projects from the command line

From an empty directory, create a new maven project

mvn archetype:generate -DgroupId=myGroup -DartifactId=myApp -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Replace myGroup and myApp with whatever you like. These values need to be all one word, and avoid punctuation. Group is for your organization - you can use your first name for school projects. Artifact ID is for the project name.

This should result in a myApp directory. Open in your editor. Code goes in the src/maon/java/myGroup/ directory. There should be a App.java file with an example main method in.

Open your pom.xml file. Copy the .... tag - lines 25 through 74 from this pom.xml https://github.com/minneapolis-edu/mvn-cmd/blob/master/pom.xml into your pom.xml. Notice how the tags are nested, and follow the structure in this example. Edit the main class (line 47) if your groupID and name are different.

Build and package your code with mvn clean package

Execute with java -jar target/myApp-1.0.SNAPSHOT.jar or for Windows java -jar target\myApp-1.0.SNAPSHOT.jar

Replace with your app's JAR file name, if different.

Code with GUIs

IntelliJ's GUI designer uses code that's not part of the standard library. I think there's a workaround to run this code from the command line, but I forgot how to do it.

SO if you figure it out, let me know :) OR know that you can build GUIs entirely in code. Examples, tutorial: http://zetcode.com/tutorials/javaswingtutorial/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment