How to run a packaged java file
Can anyone help me on how I have to run a java application which is in a package, from cmd? Please give me the necessary line that I have to type.
EDIT开发者_开发问答: (Copied a clarifying comment from one of the answers below)
No I mean a normal Java aplication that belongs to a package, like:
package x; class SampleOnly{ }
How you compile (and run) that file.
No i mean a normal java aplication that belongs 2 a package, like
package x; class sampleOnly{ }
hw u comple dat file
This little "bash session" should explain it:
$ ls . # Current directory contains the "x" package
x
$ ls x # The "x" package contains a Sample.java file...
Sample.java
$ cat x/Sample.java # ...which looks like this.
package x;
public class Sample {
public static void main(String... args) {
System.out.println("Hello from Sample class");
}
}
$ javac x/Sample.java # Use "/" as delimiter and
# include the ".java"-suffix when compiling.
$ java x.Sample # Use "." as delimiter when running, and don't include
# the ".class" suffix.
Hello from Sample class
$
How to execute an arbitrary jar file, depends on how the jar file in question is pcakaged:
If it's packaged with a manifest containing a Main-class declaraton, you simply do
java -jar program.jar
If it's a regular jar-file you need to know the main class. Let's say it's package.Main
:
java -cp program.jar package.Main
(I answered this (indirectly) here: How to convert Java program into jar?) -->
A simple class is written as:
package com.demo.pack;
public class Demo {
public static void main(String[] args) {
System.out.println("Demo class from package : '"
+ Demo.class.getPackage().getName() + "'");
}
}
This Demo class will be stored under these folders.. Folder sequence will be com/demo/pack. Then the class will be found under pack folder. Now open the command prompt.. I have stored that package in my 'D' drive. Type the following command.
D:>javac com/demo/pack/Demo.java -- press enter
D:>java com.demo.pack.Demo-- press enter..
Done!
By package you mean a .jar file?
java [ options ] <class> [ arguments ... ]
java [ options ] -jar <file.jar> [ arguments ... ]
javaw [ options ] <class> [ arguments ... ]
javaw [ options ] -jar <file.jar> [ arguments ... ]
Running Java applications
If it is a jar that you are talking about then java -jar filename.jar
And not to forget setting the main class and optional classpath in META-INF/MANIFEST.MF
Main-Class: org.example.HelloWorld
Class-Path: greetings.jar
Have a look to the JAR specs at http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html
精彩评论