Java command line compilation and execution Program
Before learning how to use java to use IDE, it is best to use the javac and java of the command line to run a simple program, so that you can familiarize yourself with the impact of package management on the. class file path.
Let's write a simple piece of code:
package com.csdn.lkasdolka;public class test_1{ public static void main(String[] args){for(int i = 0; i < 10; ++i ){ System.out.println(i);} }}
Save it as test_1.java. In windows, WIN + R open the command line and cd It To The test_1.java directory.
Use commands
javac test_1.java
Compile the file. If the java environment has been configured, input dir in the command line. We can see that there is an additional test_1.class file in the directory:
.
.. 454 test_1.class2014/10/06 173 test_1.java 2 files 627 bytes 2 directories 13,711,450,112 available bytes
Use
java test_1
An exception occurred while trying to run the bytecode file.
Exception in thread "main" java.lang.NoClassDefFoundError: test_1 (wrong name: cn/bupt/d10_1006_1/test_1) 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)
This is because
com.csdn.lkasdolka
. A package is a mechanism used in java to manage namespaces. We need to manually create com \ csdn \ lkasdolka in the current folder, and then cut test_1.class to the com \ csdn \ lkasdolka \ directory.
Then cd back to the original working directory (the parent directory of com), and enter
java com.csdn.lkasdolka.test_1
Or
java com/csdn/lkasdolka/test_1
The correct output result should be displayed:
C:\Users\acer\Desktop\technology\test_java>java com.csdn.lkasdolka.test_10123456789C:\Users\acer\Desktop\technology\test_java>java com/csdn/lkasdolka/test_10123456789
Summary:
1. javac is used to compile the. java file to generate the. class file (bytecode file). java is used to execute the. class file and remove the. class suffix during execution.
2. If a package is defined in the source file, you need to put the. class file in the corresponding directory of the package definition. Otherwise, the NoClassDefFoundError exception occurs when you execute the java command.
The End ~
(If any error occurs, please correct it)