简体   繁体   中英

How to compile Java programs from Eclipse using terminal on a Mac

I am trying to learn how to compile Java programs made on Eclipse, an IDE, in Terminal. Starting out right after opening terminal, what are the steps I should take to compile a program I've made on Eclipse in terminal? Thanks for the help.

UPDATE: I got as far as navigating to my java folder, and to the package that houses my programs, and did the line javac Hello.java (Hello is the basic "Hello World" program I'm trying to compile) but when I do java Hello I get a large error:

Exception in thread "main" java.lang.NoClassDefFoundError: Hello (wrong name: homeWorkPackage/Hello) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

What did I do wrong?

According to the official tutorials (assuming you have the JDK properly configured:

  • Change the directory to the directory where your file is saved (using the cd command)
  • Use the command javac [filename.java] to compile the program
  • there should be a class file in the directory now

If you are using eclipse, compiling from the terminal is not needed, however you can do it like this:

Navigate to the project directory containing the .java files. You can then run javac ClassName.java eg javac Cake.java javac is the Java language compiler. This command will compile the source (your .java file). To run it you can go java ClassName . eg java Cake . java starts the JVM . The named class will be loaded and execution started. You don't include the .class file extension one the java ClassName command.

When you need you navigate around the file system I think this page gives a good overview of the commands but here are a few that you might need for this task:

cd - change directory (followed by directory name) eg cd Documents

ls - list information about files (can take some parameters)

.. can take you back a directory. eg cd .. will bump you back one directory

you can also hit tab to auto complete a directory/file name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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