Published 17 Sep, 2022

Java - making a java package in the command line

Category Java
Modified : Sep 29, 2022
9

Though it's probably reccomended one uses and IDE for coding advanced java projects, I personally prefer running almost entirely command-line (using gedit as a text-editor). So please don't just tell me "Just use eclipse!" or something :P

My question is what the method of creating a package in java is by a command.

I'm not talking about packaging an application that runs in the command line, I'm talking about making a package in the command line. Am I making a text file? Am I making a directory?

Relatedly, how does one link to related libs and natives without use of an IDE?

I know I'm being really awkward here, but I really prefer the control one gets working in command line.

Answers

There are 4 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Linux, Java, Command Line, Package. These have been categorized in sections for a clear and precise explanation.

37

packages are just directories on the filesystem. so your package: com.mycompany.util corresponds to a directory com/mycompany/util.

When running and compiling etc your current workding directory should be where that top directory is located.

To include libraries, include them in your classpath when compiling and running. For example make a Project directory myproject and under that have your java-files and packages under myproject/src/ and libraries that you use under myproject/libs/ Then when your current workding directory is myproject execute java -cp .:libs/*.jar or the same with javac.

But I suggest you look into using ant or maven.


39

Java Package is just a directory structure, so a simple way of creating a Package lets say com.organization.test in terminal will be

mkdir -p com/organization/test

38

// to create a new directory and a subfolder that will be your package

$ mkdir -p parent/child 

// to move into it :

$ cd parent/child                    

//to create an empty java file

$ touch MyClass.java

//to edit current file

$ nano MyClass.java

package child; 
 public class MyClass { 
}

PS: The directory structure on your computer is related to the package name. That means when you edit .java file it needs to have a package declaration(your package) otherwise you will have a default package (ex: java.util.*).


31

You can get along just fine on the command line by using a packaging tool such as Ant or Maven. Maven is especially handy because it is a higher level tool that already knows how to build various project types: command-line apps, webapps, libraries, etc. It also handles library dependencies by downloading them from repositories.