java
一、首先安装好jdk,设置相应的环境变量
安装完Java之后,需要设置一些系统环境变量。
1、PATH
设置PATH环境变量即将JDK安装目录下的bin目录添加到操作系统的PATH中
把JDK的bin目录添加到PATH中,目的是为了在任何路径下都能使用JDK的各种命令,而不用输入完整的冗长的路径名来使用JDK的命令,比如javac、java、javac等命令。基于这一点可以安装多个版本的JDK,只要将它们安装在不同的路径下,使用时输入完整的路径来执行相应的JDK命令即可。
PATH的设置是可选的,如果不用JDK的命令工具而用eclipse等IDE工具开发JAVA,可以不用设置Path,视情况而定。
2、CLASSPATH
java在编译和运行时需要找到所用到的类,CLASSPATH是java寻找类的依据,JAVA按照设置的目录又前往后一个一个查找,并使用找到的第一个匹配的类。
CLASSPATH有两种设置方式,一种是设置为环境变量,即在操作系统的环境变量中添加CLASSPATH,另一种是使用java和javac命令的-class参数。
二、命令行下编译java程序
1、示例1(最简单的方式):用记事本之类的编写好java源文件,例如hello.java
public class hello{
public static void main(String[] args){
System.out.println("hello,world!");
}
}
在正确设置了path和classpath之后即可执行如下命令:
javac hello.java
java hello
当然可以用-d参数来制定生成的example.class存放的位置,具体可以用java -help查看
2、示例2:用包来管理类。java用包来组织管理大量的类,package就是java的命名空间,下面编写两个类:
A.java和B.java:
package com.javacore.ch2;
public class A{
public static void main(String[] args){
String hello;
hello = B.hi("China");
System.out.println(hello);
}
}
package com.javacore.ch2;
public class B{
public static String hi(String name){
return "hello," + name + ".";
}
}
编译时使用列表文件方式(之前没用过,觉得这个挺高级的):
编写一个文本文件把要编译的java源文件列在其中,类似如下(可用相对或绝对路径):
src\A.java
src\B.java
保存为srclist.txt
下面开始编译,-d参数指定class存放目录:
javac -d classes @srclist.txt
运行程序:这里需要注意一下,由于用包来管理java类,因此生成的类名类似“com.javacore.ch2.A”,因此不能直接运行java A,为了能让java命令找到类A,需要临时设置CLASSPATH,类似:set CLASSPATH=D:\用户目录\java\classes,即把存放class的路径添加到CLASSPATH中,设置好CLASSPATH之后即可运行如下命令:
java com.javacore.ch2.A
完成上述操作后,可进入classes目录将类打包,供后续使用。打包如下:
3、示例3:使用第三方库的情况,可先将第三方类库复制到lib目录下,然后编写源码调用该库
编写C.java调用类B
package com.javacore.ch2.cc;
import com.javacore.ch2.B;
public class C{
public static void main(String[] args){
String hello;
hello = B.hi("CC");
System.out.println(hello);
}
}
编译:
需要设置临时CLASSPATH将生成的类和调用的第三方类都加入其中。。
以前一直使用eclipse写java,对这些过程不是很清楚,现在总算有点清晰了~