Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compile and run a Java class in a different directory?

Tags:

java

javac

I'm writing a makefile that compiles a .java file in a different directory, and then I want to run it, without changing directories. I want to do something along the lines of:

$(SQM_JAVA_TOOL_DONE) : $(SQM_JAVA_TOOL)         $(shell cd /home_dir)         javac myjavafile.java         java myjavafile 

where the Java file is /home/myjavafile.java, and the makefile isn't running from /home.

How can I do this?

like image 511
vette982 Avatar asked Aug 05 '10 14:08

vette982


People also ask

How do I run a Java program from another drive?

Go to advance setting and click environment variable tab. Now once u add this search an existing variable path and choose edit. Now at the end append the following ;%JAVA_HOME%\bin Now ur done u cn run java program frm any location on ya comp.... Show activity on this post.

How do you compile and run a Java class?

Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.

How do I run a Java class in a jar classpath?

To run an application in a nonexecutable JAR file, we have to use -cp option instead of -jar. We'll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute: java -cp jar-file-name main-class-name [args …]


2 Answers

I might be misunderstanding the question, but you can compile with

javac /home/MyJavaFile.java 

This will create MyJavaFile.class in /home

You can then run it by including /home on the classpath. e.g.

java -cp /home MyJavaFile 

If you want to generate the class file in a different directory then you can use the -d option to javac.

like image 200
mikej Avatar answered Sep 21 '22 00:09

mikej


Use the -d command line parameter with javac to tell it what directory you'd like to store the compiled class files in. Then, to run the program, simply include this directory in the classpath:

javac -d some/directory myjavafile.java java -cp some/directory myjavafile 
like image 21
Michael Avatar answered Sep 25 '22 00:09

Michael