[英]How do I run a Java program on Terminal (Mac)?
I am new to Java (as of today!) and am trying to run a very simple program in terminal. 我是Java的新手(截至今天!),我正试图在终端中运行一个非常简单的程序。 Normally, when I run a python (still pretty new) program in Terminal I would simple type in "python name.py" in to terminal and it would run. 通常,当我在终端I中运行python(仍然很新)程序时,只需在“终端中输入”python name.py“即可运行。 When I type "Java name.java" it does absolutely nothing. 当我输入“Java name.java”时,它什么都没做。
I opened TextWrangler and selected "Run in Terminal" and it returned this error: 我打开TextWrangler并选择“Run in Terminal”并返回此错误:
"This file doesn't appear to contain a valid 'shebang' line (application error code: 13304)" “此文件似乎不包含有效的'shebang'行(应用程序错误代码:13304)”
My program is named "hello.java" and it contains the code below. 我的程序名为“hello.java”,它包含以下代码。
What am I doing wrong? 我究竟做错了什么?
System.out.println("Hello!");
Open the terminal, go to the directory where the file is located and do this: 打开终端,转到文件所在的目录并执行以下操作:
javac -classpath . name.java // compile the code
java name // run the program
Of course, both javac
and java
must be available in the operating system's PATH variable, but in a Mac that's already configured. 当然, javac
和java
必须在操作系统的PATH变量中可用,但在已经配置的Mac中。
Type 类型
javac helloworld.java
java helloworld
The first line calls the compiler and compiles it in the current directory then the next line runs it 第一行调用编译器并在当前目录中编译它,然后下一行运行它
"Run in terminal" attempts to run the software as an interpreted script. “在终端中运行”尝试将软件作为解释脚本运行。 On UNIX-like systems (meaning almost everything except Windows), a shebang line is used to indicate, what interpreter is to be used. 在类UNIX系统(几乎所有除Windows之外的所有系统)上,使用shebang行来指示要使用的解释器。 It consists of the characters #!
它由人物#!
组成#!
followed by the command to invoke the interpreter (eg #!/usr/bin/python
or #!/usr/bin/ruby
). 然后是调用解释器的命令(例如#!/usr/bin/python
或#!/usr/bin/ruby
)。 However, Java is not (only) interpreted. 但是,Java不会(仅)解释。
java
only runs compiled Java bytecode , so it does not work on source files java
只运行编译的Java字节码 ,因此它不适用于源文件
Instead, head over to the terminal yourself, compile the code with javac
and run the resulting bytecode (the .class
files) with java
: 相反,请自己前往终端,使用javac
编译代码并使用java
运行生成的字节码( .class
文件):
javac the_file_name.java
java the_class_name
where the_file_name.java
is the file containing main(...)
and the_class_name
is the name of the class containing main(...)
(this should usually be the same as the_file_name
) 其中the_file_name.java
是包含该文件main(...)
和the_class_name
是包含类的名称main(...)
这通常应该是一样的the_file_name
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.