简体   繁体   English

如何在 Windows 上使用单个命令行编译和运行 Java

[英]How to compile and run Java with single command line on Windows

Everytime I want to build and run my program I do:每次我想构建和运行我的程序时,我都会这样做:

javac myProgram.java
java myProgram

I want to do something like this:我想做这样的事情:

buildrun = javac (some_argument).java && java (some_argument)

so after I can just所以在我可以之后

buildrun myProgram

How to achieve this on Windows?如何在 Windows 上实现这一点?

As other's have suggested you can simply create a batch file to build and run your program.正如其他人所建议的那样,您可以简单地创建一个批处理文件来构建和运行您的程序。 Copy this in Notepad and save as .bat.将此复制到记事本中并另存为 .bat。

@echo off
set /p class="Enter Class: "
javac "%class%".java
java "%class%"

As you want, the batch file will ask for a FileName when it runs.如您所愿,批处理文件在运行时会要求提供 FileName。 In your case, you can set it to 'myProgram' and it will then compile and run the program.在您的情况下,您可以将其设置为“myProgram”,然后它将编译并运行该程序。

Just make sure your batch file and your java file reside in the same folder for this script to run.只需确保您的批处理文件和您的 java 文件驻留在同一文件夹中即可运行此脚本。 You can always tweak the bat file to even accept the full path of the Java file.您可以随时调整 bat 文件以接受 Java 文件的完整路径。

要在 cmd 中使用单个命令行编译和运行 Java,请使用:java myProgram.java

You can use Makefile this way:您可以这样使用Makefile

  1. Create a file named Makefile within the same folder where your java files reside.在 Java 文件所在的同一文件夹中创建一个名为Makefile的文件。
  2. Add these contents to Makefile将这些内容添加到Makefile
run: compile
    java $(class)

compile: 
    javac $(class).java
  1. From terminal, run this command: make run class=myProgram从终端运行以下命令: make run class=myProgram

This way, it will compile first then run your java class in a single command这样,它将首先编译,然后在单个命令中运行您的 java 类

Yet another solution.另一个解决方案。 Create buildrun.cmd file with the following code:使用以下代码创建buildrun.cmd文件:

@echo off
javac %1.java
if errorlevel = 0 goto RUN

:ERROR
echo "Build fails!"
goto END

:RUN
java %1

:END

Now you can pass the class name which should be processed.现在您可以传递应该处理的类名。 For example: buildrun MyProgram to compile MyProgram.java and run MyProgram.class In this case execution will performs only if your class was compiled successful.例如: buildrun MyProgram编译MyProgram.java并运行MyProgram.class在这种情况下,只有当您的类编译成功时才会执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM