不含包层次的helloworld.java
public class helloworld{ public static void main(string[] args) { system.out.println("hello world!"); }}
保存在e:/java/src下,使用javac命令编译:
e:/java/src>javac helloworld.java
运行:
e:/java/src>java helloworld
屏幕打印出:
hello world!
初学者常犯的错误
1. 运行时,带了.class后缀
如果你试图使用如下命令:
e:/java/src>java helloworld.class
系统会误认为你运行的是helloworld包下的名为class的类文件,会到系统的classpath下(一般都包括当前目录)企图寻找helloworld.class.class这样的类,这样的类当然不存在了;并且也不可能存在,因为class是关键字,不能作为一个类的名字。所以会报如下错误信息:
exception in thread "main" java.lang.noclassdeffounderror: helloworld/class
2. 文件名大小写错误
对于像windows这样的系统,编译时可以不关心大小写。比如编译helloworld.java时,也可以使用:
e:/java/src>javac helloworld.java
也可以编译通过,但产生的类文件仍然是和源文件相符的:helloworld.class。
但在运行时一定要注意大小写,比如试图使用如下命令运行:
e:/java/src>java helloworld
将报类似于1中的错误:
exception in thread "main" java.lang.noclassdeffounderror: helloworld (wrong name: helloworld)
包含包层次的helloworld.java
比如上面的helloworld.java修改如下:
package org.javaresearch;public class helloworld{ public static void main(string[] args) { system.out.println("hello world!"); }}
编译时有两种方法
1. 直接编译
e:/java/src>javac helloworld.java
此时在当前目录下输出helloworld.class。此时,运行不能使用上面相同的方法,使用:
e:/java/src>java helloworld
运行时,出现如下错误:
exception in thread "main" java.lang.noclassdeffounderror: helloworld (wrong name: org/javaresearch/helloworld)
从上述错误信息你也可以看到,系统可以找到helloworld类(因为当前路径包含在classpath中,具体为什么会提示wrong name,有兴趣的朋友参见java语言规范),但这个类属于org.javaresearch包。所以,你要做的就是按照上述包层次,相应的创建目录层次,把上面生成的helloworld.class放到e:/java/src/org/javaresearch/目录下。运行:
e:/java/src >java org.javaresearch.helloworld
系统打印出:
hello world!
这儿要注意的是,不能使用java org/javaresearch/helloworld来运行,此时同样会出现如下错误:
exception in thread "main" java.lang.noclassdeffounderrorrg/javaresearch/helloworld (wrong name: org/javaresearch/helloworld)
哈哈,是不是有点怪怪的,那没办法。以后对java的包有更深的认识时,就会明白了。
2. 使用 -d <directory>编译选项
是不是觉得上面的编译方法有点麻烦,能不能自动在当前路径(或任意指定的路径)下生成包层次呢?有!使用-d <directory>编译选项就能做到。
e:/java/src >javac -d . helloworld.java
此时,在当前目录下就生成了一个org/javaresearch目录,并且输出的.class文件也在里面。运行:
e:/java/src >java org.javaresearch.helloworld
系统打印:hello world!
如果你想把生成的类文件集中存放在一个目录中,比如:e:/java/classes下,那么你首先创建这个目录,然后编译时:
e:/java/src >javac -d e:/java/classes helloworld.java
就可以把生成的类文件放到e:/java/classes目录下,并且按照包层次相应的创建目录路径。你可以在e:/java/classes/org/javaresearch下找到helloworld.class文件。此时使用如下命令可以正确运行(注意如果要用到其它类,请在classpath中设好):
e:/java/classes >java org.javaresearch.helloworld
闽公网安备 35060202000074号