Compile and build with single command line Java (L

2020-08-26 03:02发布

Is there way to set up an alias in such a way so that I could enter the command, followed by the argument in a single line?

For example, instead of

javac Program.java && java Program

I would be able to go

newcommand Program.java //or "newcommand Program", whichever is easier

which would do the same commands as the line above.

7条回答
孤傲高冷的网名
2楼-- · 2020-08-26 03:38

I was going to answer you giving a piece of Makefile, but it would not be generic enough. Whenever you want to compile a more complex program (let's say 2 files), you need to compile the second as well. It might be in a package, in which case what you're asking does not work any longer. Same thing if you have to handle libraries.

For all these reasons, I strongly advise you to choose a building utility of your choice, make, scons, ant, and let's mention it maven. I find the later way to complex for small projects. But ant is my best candidate for java programs. In the end, you can just ant run which will run your program and recompile it if needed. Have a look on the hello world tutorial with ant.

查看更多
爷的心禁止访问
3楼-- · 2020-08-26 03:40

Adding on to enrico.bacis' and notcompletelyrational's answer, how to run it under a package and clean up the package compiled files:

jcar() { javac -d . $1.java && java ${PWD##*/}.$1 && rm -rf ${PWD##*/}/ }

By the way, this function should be added to ~/.bash_profile for Mac OS and ~/.bashrc for Linux, respectively.

To run it:

jcar ProgramName
查看更多
可以哭但决不认输i
4楼-- · 2020-08-26 03:42

I like to pass the full Program.java filename as the input parameter, allowing easy autocompletion.

Here's an edited version of notcompletelyrational's script, which expects commands like jcar Program.java rather than jcar Program:

jcar() {
  f=$1
  f2=${f%.*}
  trap "rm $f2.class" SIGINT SIGTERM
  javac $1
  java $f2
  rm $f2.class
}
查看更多
淡お忘
5楼-- · 2020-08-26 03:44

Adding on to enrico.bacis' answer, i personally don't like to have Program.class files cluttering up my workspace if i'm just testing a program, so i'd do

jcar() { javac $1.java && java $1 && rm $1.class}

in addition, i found it helpful to trap ctrl-c so that even if i end the program halfway, it still removes the .class

jcar() {
trap "rm $1.class" SIGINT SIGTERM
javac $1.java
java $1
rm $1.class
}
查看更多
成全新的幸福
6楼-- · 2020-08-26 04:00

An alias is not made to accept parameters, define a function like this:

jcar() { javac $1.java && java $1 ; }

Then use it:

jcar Program

(jcar was intended as an acronym for java-compile-and-run)

查看更多
何必那么认真
7楼-- · 2020-08-26 04:01

My favorite solution looks like this:

function jcar { javac ${1%.*}.java && java ${1%.*}; }

It can handle various inputs, such as

jcar myfile
jcar myfile.
jcar myfile.java
jcar myfile.class

It lets you use Tab more quickly :)

查看更多
登录 后发表回答