How to run a .class file in Windows 7 OS?
This is probably a stupid question, but how do I run a class file on windows 7? I usually create my own .java files and then use a basic IDE (with JDK6) to compile it to a class and run it automatically. My professor gave a .class file that we are supposed to play with extensively but I have no idea h开发者_Go百科ow to to run it here. Note that I cannot run it by typing:
java classname.class
because it contains gui stuff especially buttons and such. If I do the above I get the following error:
java.lang.NoClassDefFoundError: Test1/2/class
Caused by: java.lang.ClassNotFoundException: Test1.2.class
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: Test1.2.class. Program will exit.
Exception in thread "main"
Any help would be highly appreciated. Thanks.
When you run it, don't include the .class
suffix:
java classname
In addition to the above, it should also make no odds what your O/S is. Java compiles to byte code, which is interpreted by your JVM. You clearly have one installed since you got the java error you have pasted above.
Like codeka said, you need to type java ClassName
at the command line, and if the class has a main method, it will be run.
Java compiles each class that is defined in a particular source file into its own class (byte code) file. For example, Apple.class, Banana.class, and Cherry.class might get output after compiling Apple.java, if they are all defined there. So the actual name of the class in source will match the name of the file, minus the extension.
Now, let's say that someone accidentally (or intentionally, from the sound of it) renamed the class file. You have a file called WrongName.java, and you type java WrongName
. Note that the output will begin with the line:
Exception in thread "main" java.lang.NoClassDefFoundError: WrongName (wrong name: RightName)
Where RightName is what it should be. At that point you would rename your file to RightName.class, type java RightName
, and hopefully it will run. And if the name has a slash, then whatever precedes the slash is the name of the package. Let's say it's PackageName/RightName. First you need to create a directory called PackageName, and put RightName.class inside of it. Then, go one level up in your directories, and type java PackageName.RightName
.
Note the different kinds of exceptions: ClassNotFoundException
basically means that the class file was not found. NoClassDefFoundError
means that the class definition was not found. If the class does not have a main method and you try to run it as a program, you will get NoSuchMethodError: main
.
精彩评论