从命令行执行 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4225815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:23:49  来源:igfitidea点击:

Execute Java from command line

javaunixcommand-line

提问by CodeGuy

I have a folder on my desktop titled "Stuff" and in that folder I have the following:

我的桌面上有一个名为“Stuff”的文件夹,在该文件夹中我有以下内容:

  • Hello.java
  • mail.jar
  • 你好.java
  • 邮件文件

And Hello.java imports from mail.jar, so I need to tell Hello.java to look for mail.jar.

而Hello.java 从mail.jar 导入,所以我需要告诉Hello.java 去寻找mail.jar。

From a Windows command line and from a unix command line, how can I compile this and run this?

从 Windows 命令行和 unix 命令行,我如何编译并运行它?

回答by T.J. Crowder

Compile:

编译:

javac -cp .;mail.jar Hello.java

where ;is for Windows; use :for *nix.

;Windows在哪里;使用:在* nix。

and run:

并运行:

java -cp .;mail.jar Hello

where again, use ;for Windows and :for *nix.

再次,;用于 Windows 和:*nix。

-cptells both javacand javawhat classpathto use, and as your files are in the local directory where you're executing the command, you can use .for the Hello part and the name of the jar for the paths inside the jar. Wikipedia has a decent article on classpaths.

-cp告诉双方javacjava什么类路径中使用,并为您的文件在本地目录你在哪里执行命令,你可以使用.Hello保持部分和罐子罐子里面的路径名。维基百科有一篇关于类路径不错的文章

Mind you, if you're going to be doing this on a regular basis, you may want to set your CLASSPATHenvironment variable rather than constantly using the -cpflag. Both javaand javacuse the CLASSPATHvariable.

请注意,如果您打算定期执行此操作,您可能希望设置CLASSPATH环境变量而不是经常使用该-cp标志。两者javajavac用的CLASSPATH变量。

For my own development machine, I actually include .in my CLASSPATHvariable, for convenience. It's not something I would do on a production or build/test box, but it's very handy for development purposes. You'd want to have your usual jars in it as well.

对于我自己的开发机器,为了方便起见,我实际上将其包含.在我的CLASSPATH变量中。这不是我会在生产或构建/测试盒上做的事情,但它对于开发目的非常方便。你也想在里面放你常用的罐子。

回答by Michael Borgwardt

Assuming Hello.java does not contain a package declaration, on Windows:

假设 Hello.java 不包含包声明,在 Windows 上:

javac -cp mail.jar Hello.java
java -cp mail.jar;. Hello

The only difference on Unix platforms is that you separate the elements of the classpath with a scolon instead of a semicolon:

Unix 平台上的唯一区别是您用冒号而不是分号分隔类路径的元素:

java -cp mail.jar:. Hello

回答by Richard

Follow this tutorial and you should be able to do it in no time:

按照本教程,您应该可以立即完成:

Java Compilation

Java编译

You also shouldn't have any problems with the classpath because your classes are in the same folder

您也不应该对类路径有任何问题,因为您的类位于同一文件夹中