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

后端 未结 3 1667
孤独总比滥情好
孤独总比滥情好 2020-12-01 06:20

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 alo

相关标签:
3条回答
  • 2020-12-01 06:59

    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.

    0 讨论(0)
  • 2020-12-01 07:06

    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
    
    0 讨论(0)
  • 2020-12-01 07:08

    Just to add to the existing answers, you may want the --source-path flag:

    --source-path <path>, -sourcepath <path>
          Specify where to find input source files
    

    I believe this effectively sets the package root javac will compile from (i.e. <path> will be stripped from the expected package name of the files). It's still necessary to enumerate the files to compile, and this should still be relative to the current working directory, not the path passed to --source-path.

    For example, to compile and run from a project's root where source is stored in src/ and you want it build in bin/:

    $ javac --source-path src -d bin src/mypackage/*.java
    $ java -cp bin mypackage.Main
    

    This works even from directories elsewhere in the filesystem, e.g.:

    $ javac --source-path /some/absolute/path/src  -d /some/absolute/path/bin /some/absolute/path/
    $ java -cp /some/absolute/path/bin mypackage.Main
    
    0 讨论(0)
提交回复
热议问题