How to create and use library JAR files with command-line tools?

Development Tools -> General Questions:
I am trying to figure out how to put utility classes into JAR files and then compile and run applications against those JAR files using the command-line javac, jar, and java tools. I am using jdk1.7.0_17 on Debian GNU/Linux 6.0.7.
I have posted a simple example with one utility class, one console application class, and a Makefile:
http://holgerdanske.com/users/dpchrist/java/examples/jar-20130520-2134.tar.gz
Here is a console session:
2013-05-20 21:39:01 dpchrist@desktop ~/sandbox/java/jar
$ cat src/com/example/util/Hello.java
package com.example.util;
public class Hello {
    public static void hello(String arg) {
     System.out.println("hello, " + arg);
2013-05-20 21:39:12 dpchrist@desktop ~/sandbox/java/jar
$ cat src/com/example/hello/HelloConsole.java
package com.example.hello;
import static com.example.util.Hello.hello;
public class HelloConsole {
    public static void main(String [] args) {
     hello("world!");
2013-05-20 21:39:21 dpchrist@desktop ~/sandbox/java/jar
$ make
rm -f hello
find . -name '*.class' -delete
javac src/com/example/util/Hello.java
javac -cp src src/com/example/hello/HelloConsole.java
echo "java -cp src com.example.hello.HelloConsole" > hello
chmod +x hello
2013-05-20 21:39:28 dpchrist@desktop ~/sandbox/java/jar
$ ./hello
hello, world!I believe I am looking for:
1. Command-line invocation of "jar" to put the utility class bytecode file (Hello.class) into a JAR?
2. Command-line invocation of "javac" to compile the application (HelloConsole.java) against the JAR file?
3. Command-line invocation of "java" to run the application (HelloConsole.class) against the JAR file?
I already know how t compile the utility class file.
Any suggestions?
TIA,
David

I finally figured it out:
1. All name spaces must match -- identifiers, packages, file system, JAR contents, etc..
2. Tools must be invoked from specific working directories with specific option arguments, all according to the project name space.
My key discovery was that if the code says
import com.example.util.Hello;then the JAR must contain
com/example/util/Hello.classand I must invoke the compiler and interpreter with an -classpath argument that is the full path to the JAR file
-classpath ext/com/example/util.jarThe code is here:
http://holgerdanske.com/users/dpchrist/java/examples/jar-20130525-1301.tar.gz
Here is a console session that demonstrates building and running the code two ways:
1. Compiling the utility class into bytecode, compiling the application class against the utility bytecode, and running the application bytecode against the utility bytecode.
2. Putting the (previously compiled) utility bytecode into a JAR and running the application bytecode against the JAR. (Note that recompiling the application against the JAR was unnecessary.)
(If you don't know Make, understand that the working directory is reset to the initial working directory prior to each and every command issued by Make):
2013-05-25 14:02:47 dpchrist@desktop ~/sandbox/java/jar
$ cat apps/com/example/hello/Console.java
package com.example.hello;
import com.example.util.Hello;
public class Console {
    public static void main(String [] args) {
     Hello.hello("world!");
2013-05-25 14:02:55 dpchrist@desktop ~/sandbox/java/jar
$ cat libs/com/example/util/Hello.java
package com.example.util;
public class Hello {
    public static void hello(String arg) {
     System.out.println("hello, " + arg);
2013-05-25 14:03:03 dpchrist@desktop ~/sandbox/java/jar
$ make
rm -rf bin ext obj
mkdir obj
cd libs; javac -d ../obj com/example/util/Hello.java
mkdir bin
cd apps; javac -d ../bin -cp ../obj com/example/hello/Console.java
cd bin; java -cp .:../obj com.example.hello.Console
hello, world!
mkdir -p ext/com/example
cd obj; jar cvf ../ext/com/example/util.jar com/example/util/Hello.class
added manifest
adding: com/example/util/Hello.class(in = 566) (out= 357)(deflated 36%)
cd bin; java -cp .:../ext/com/example/util.jar com.example.hello.Console
hello, world!
2013-05-25 14:03:11 dpchrist@desktop ~/sandbox/java/jar
$ tree -I CVS .
|-- Makefile
|-- apps
|   `-- com
|       `-- example
|           `-- hello
|               `-- Console.java
|-- bin
|   `-- com
|       `-- example
|           `-- hello
|               `-- Console.class
|-- ext
|   `-- com
|       `-- example
|           `-- util.jar
|-- libs
|   `-- com
|       `-- example
|           `-- util
|               `-- Hello.java
`-- obj
    `-- com
        `-- example
            `-- util
                `-- Hello.class
19 directories, 6 filesHTH,
David

Similar Messages

  • HOW TO CREATE  and  USE EVENTS IN WORKFLOWS .

    HOW TO CREATE  and  USE EVENTS IN WORKFLOWS with the help of classes.
    What i am doing is..
    open se24
    event tab->event name->parameters
    method tab->method name->event handler->copy parameters
    interface tab->if_workflow->enter
    tell me what else to do step by step
    Another important thing is that HOW to use these class events to trigger the workflows.
    REPLY ASAP
    THXS IN ADVANCE

    Hi,
    Pl. see this blog...
    Raising ABAP OO events for workflow
    Regards,
    JOy.

  • How To Run An External .exe File With Command Line Arguments

    Hiya, could anyone tell me how I can run an external .exe file with command line arguments in Java, and if possible catch any printouts the external .exe file prints to the command line.
    Thanks.

    Using the Runtime.exec() command. And read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • How to create and use dynamic queue in JMS

    Plz tell me how to create and use a dynamic queue in jms and can reciever file lookup it as it lookup any server configurred queue(written in the server).

    Hi,
    We can use Azure File services to do this, for more information, please have a look at this article:
    http://blogs.msdn.com/b/windowsazurestorage/archive/2014/05/12/introducing-microsoft-azure-file-service.aspx. The Azure File service exposes file shares using the standard SMB 2.1 protocol. Applications running in Azure can now easily share files between
    VMs using standard and familiar file system APIs like ReadFile and WriteFile.
    Best Regards,
    Jambor
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Gridworld Case Study - how to use a .jar file with textpad

    Hello,
    I am a student currently working on a project involving the Gridworld case study. While trying to work on my project at home, I discovered that I would get new "cannot find symbol" compiler errors that I had not previously gotten while compiling the same code at school. I am assuming this has something to do with the .jar file included in the gridworld code. How do I get textpad and/or the java compiler to find and use the .jar file and reccognise the classes which i am importing and extending in my project?
    Thanks,
    -Alex

    Thanks, It works for compiler now.
    Now, I write a html to run the applet. appletviewer
    says "
    java.lang.NoClassDefFoundError: ij/process/ImageProcessor
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:1590)
    at java.lang.Class.getConstructor0(Class.java:1762)
    at java.lang.Class.newInstance0(Class.java:276)
    at java.lang.Class.newInstance(Class.java:259)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:566)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:495)
    at sun.applet.AppletPanel.run(AppletPanel.java:292)
    at java.lang.Thread.run(Thread.java:536)
    It seems the appletviewer can not find the right path for the package. How can I fix this?
    Thank again,
    Hillxy

  • How to create and use mutable array of UInt8

    Hello!
    If I get it right, UInt8 *buffer, buffer - is a pointer to a start of array?
    Then how to create and use mutable array of UInt8 pointers?
    The main target is a creation of the module that will store some byte array requests and will send all of them at the propriate moment.

    I try
    - (void) scheduleRequest:(UInt8 *)request {
    if (!scheduledRequests) scheduledRequests = [[NSMutableArray array] retain];
    [scheduledRequests addObject:request];
    But get warning:"passing argument 1 of 'addObject:' from incompatible pointer type"

  • How to Create  and use of Coherence servers in weblogic serevr 11g (10.3.6)?

    how to Create  and use of Coherence servers in weblogic serevr 11g (10.3.6)?

    See the below discussion
    How to create and use Webservice controls using WSDL in weblogic portal10.3
    Thanks,
    Venkat Sarvabatla

  • How to create and manage the log file

    Hi,
    I want to trace and debug the program process.
    I write the code for creating log file and debugging the process.
    But i am not able get the result.
    please help me how to create and manage the log file.
    Here i post sample program
    package Src;
    import java.io.*;
    import org.apache.log4j.*;
    import java.util.logging.FileHandler;
    public class Mylog
         private static final Logger log = Logger.getLogger("Mylog.class");
         public static void main(String[] args) throws Exception {
         try {
           // Create an appending file handler
            boolean append = true;
            FileHandler handler = new FileHandler("debug.log", append);
            // Add to the desired logger
            Logger logger = Logger.getLogger("com.mycompany");
            System.out.println("after creating log file");     
              catch (IOException e)
                   System.out.println("Sys Err");
            }Please give the your valuable suggesstion... !
    Thanks
    MerlinRoshina

    Just i need to write a single line in log file.

  • How to handle 2 or more .jar files with an applet

    Hey out there
    I have created an ftpClient application that uses "jakarta ftpClient". It works fine as an JFrame application � But when I converted the Application into an JApplet I get the following Exception:
    java.lang.NoClassDefFoundError: org/apache/commons/net/ftp/FTPClient
    I have bundled the main application into a .jar file (Application,jar). But I don't know how to handle the 2 jakarta .jar files with my JApplet??
    I Tried to append the 2 jakarta .jar files to the Application,jar with the following code:
    jar cvf Application.jar 1.class 2.class�. commons-net-1.4.1.jar jakarta-oro-2.0.8.jar
    But with the same result / Exception (I have signed the Jar file!)
    Can anyone help me

    Hi i have a question with your application can you down- or upload more files at the same time? Because i'm having problems with my ftp application.
    Here is the link with my problem maybe you can help me. I will be very pleased when you can help me.
    http://forum.java.sun.com/thread.jspa?threadID=5162042&tstart=0
    Thx
    Satanduvel

  • How can I get a single jar file with NetBeans?

    How can I get a single jar file with NetBeans?
    When I create the project I get these files:
    dist/lib/libreria1.jar
    dist/lib/libreria2.jar
    dist/software.jar
    The libraries that have been imported to create the project are in separate folders:
    libreria1/libreria1.jar
    libreria2/libreria2.jar
    libreria1, libreria2, dist folders are all located inside the project folder.
    I added the following code to the build.xml:
    <target name="-post-jar">
    <jar jarfile="dist/software.jar">
    <zipfileset src="${dist.jar}" excludes="META-INF/*" />
    <zipfileset src="dist/lib/libreria1.jar" excludes="META-INF/*" />
    <zipfileset src="dist/lib/libreria2.jar" excludes="META-INF/*" />
    <manifest>
    <attribute name="Main-Class" value="pacco.classeprincipale"/>
    </manifest>
    </jar>
    </target>
    Of course there is also the project folder:
    src/pacco/classeprincipale.form
    src/pacco/classeprincipale.java
    Can you tell me what is wrong? The error message I get is as follows:
    C:...\build.xml:75: Problem creating jar: archive is not a ZIP archive BUILD FAILED (total time: 2 seconds)

    This is not a NetBeans forum, it is a JDeveloper forum. You might want to try http://forums.netbeans.org/. I also saw your other question - try looking in the New to Java forum: New To Java

  • Hello guys..does anybody know how to install and use adobe master collection with the new lion?   I need to use Flash and illustratore, but apparently those programmes are incompatible with the new operative sistem...   I am a new mac users and I'd like t

    Hello guys..does anybody know how to install and use adobe master collection with the new lion?
    I need to use Flash and illustratore, but apparently those programmes are incompatible with the new operative sistem...
    I am a new mac users and I'd like to know if there are other similar programmes I can use with lion!

    Lab79 wrote:
    Are you on Apple's payroll?
    well dude I can only let you know that as I work with those programme I don't have to pay for it is my company that pays the programme I whant to use( that's why I was asking if there where other programmes ..that I could use with lion insted that Illustrator and Flash!)..I know Adobe since 2005 and I can say that Adobs products are very good...I think that if it's an Adobe probleme or fault ..they will solve it very soon...but unfortunally I have the impression that after Jobs passed away Appel decided to change politics..and everything started to go very bad! (see FCP X)..
    good luck with apple dude..
    Where is the Apple problem? I have CS4 and CS5 running perfectly fine on my Macbook Pro. Installed 5 after Lion upgrade. Worth every cent. Adobe did have some catching up to do with Lion but with the CS5.5 update all runs fine. But not yours. So it is a problem with the Lion OS? You say you have been with Adobe since 2005. So you would be aware of all the other issues that Adobe had catching up with past Oss in Mac and Windows then. They get it right, but it is up to them. It is not up to Apple, nor Microsoft for that matter, to run around and check that every software developer in the world is running their business properly.
    And what has politics got to do with anything. Some people just have to blame Software for their poor Hardware maintainence of failure of the same.
    <The only think I can really do is to go back on my old windows...give back this orrible lap top and ask for my money back!>
    Great suggestion. You should go with that one, but good luck getting a refund.
    Bye

  • Import biar file with command line

    Hi
    I am trying to import biar file with command line on unix environment with BOXI R3.1 and Oracle DB
    The biar file include one universe and it's connection (eFashion), one report and one user
    when I run the command line:
    java -jar /BO/boxi/bobje/java/lib/biarengine.jar /BO/boxi/test.properties
    I recive the following error:
    Failed to commit objects to server : Undefined Info Store error
    An error occurred at the server during security batch commit:
    Request 6 of type 36 failed with server error : Object not found (1433)
    Request 11 of type 36 failed with server error : Object not found (1433)
    Request 20 of type 38 failed with server error : Object not found (1433)
    Request 26 of type 38 failed with server error : Object not found (1433)
    Do you have any idea , what is the problem?
    Thank you

    Hi Denis
    I found out after I create a biar file ,with only the user, through a command line. that the user did import since it was in a concurrent connectiontype , a type that not exit in the target environment.
    But after I fix this in the source environment and saw that a biar file with only the user is loaded , I recreate the biar file with all the objects as before (user, universe, report , folder) and I still got the same error message as before.
    So now I try to create the biar file with all those object through the command line. and I get a new errer message "Required dependencies not found on target system : '[AZK_.9sbf_lMgdQRpsbZfVw]"
    I check it , and understand that the object is the report , but I do not see what missing..... : (
    Those are the quries in the properties file:
    exportQuery= SELECT * FROM CI_APPOBJECTS where si_kind = 'Universe' and si_name='eFashion'
    exportQuery= SELECT  * FROM CI_APPOBJECTS WHERE SI_ID in ( 894,926)
    exportQuery= SELECT * from CI_SYSTEMOBJECTS WHERE SI_KIND = 'user' and SI_Name='repadmin'
    exportQuery= SELECT * FROM CI_INFOOBJECTS WHERE si_kind= 'Folder' and SI_name = 'test'
    exportQuery= SELECT * FROM CI_INFOOBJECTS WHERE      SI_ID IN (2188)
    Can you tell what is missing?

  • How to create and edit a .ini file using java

    Hi All...
    Pls help me in creating and editing an .ini file using java...
    thanks in advance
    Regards,
    sathya

    Let's assume the ini file is a mapping type storage (key=value) so lets use Properties object. (works with java 1.4 & up)
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Properties;
    public class Test {
         private static Properties props;
         public static void main(String[] args) throws IOException {
              File file = new File("test.ini");//This is out ini file
              props = new Properties();//Create the properties object
              read(file);//Read the ini file
              //Once we've populated the Properties object. set/add a property using the setProperty() method.
              props.setProperty("testing", "value");
              write(file);//Write to ini file
         public static void read(File file) throws IOException {
              FileInputStream fis = new FileInputStream(file);//Create a FileInputStream
              props.load(fis);//load the ini to the Properties file
              fis.close();//close
         public static void write(File file) throws IOException {
              FileOutputStream fos = new FileOutputStream(file);//Create a FileOutputStream
              props.store(fos, "");//write the Properties object values to our ini file
              fos.close();//close
    }

  • Data Modeller: how to create and use collection type

    Hello,
    basically subj. I'm not clear how to ( for example ) create and use the data type based off the varray data type.
    Please advise.
    thank you
    andrew

    Hi Andrew,
    you can create collection types (varray/table) in two ways:
    1) in browser - find "Data Types">"Collection types" node use pop-up menu - it's just "create new collection type" there
    2) in Data types model diagram - you can create collection of "certain structured type" or collection of references to it - use "new Collection ..." tool and first click on referred structured type and after that on structured type that will hold the collection - new attribute is added in latter type and if there is no such collection type already defined new collection type is created and you can edit it later.
    Philip

  • Executing jar file on command line [windows]

    Hi,
    I am trying to run .jar file "senthil.jar" . It catures systems screenshot.
    http://sensaran.wordpress.com/2010/06/04/screen-shot-utility-using-air-2-0/
    I am using it in AIR application. I want to execute this file from  command line. I am not sure how to pass command line arguments.
    Currently i am trying to do it like :  java -jar senthil.jar
    I need to provide a parameter as "Print Screen"
    Its corresponding Flex Code is :
                var arg:Vector.<String> = new Vector.<String>;
                arg.push("-jar");
                arg.push(File.applicationDirectory.resolvePath("senthil.jar").nativePath);
                 var file:File = new File();
                file = file.resolvePath(javaPath.replace(/\//g, File.separator));
                var npInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
                npInfo.executable = file;
                npInfo.arguments = arg;
                nativeProcess = new NativeProcess();
                nativeProcess.start(npInfo);
                nativeProcess.standardInput.writeMultiByte("Print Screen" + "\n", "utf-8");
    Thanks

    Did you give the -jar option with javaw? And the "%1"? See the file associations of some other extensions for example of how to do this
    For example on my machine,
    W:\>assoc .mp3
    .mp3=Winamp.File
    W:\>ftype Winamp.File
    Winamp.File="C:\Program Files\Winamp\Winamp.exe" "%1"Now I can
    start song.mp3Or doubleclick on mp3 file in explorer to open it in winamp.

Maybe you are looking for

  • Can i use my android to print from HP Officejet J6450 all-in one

    i have downloaded the application from android to print  using my android phone...is the ...HP Officejet J6450 all in one printer capable of doing this ....or am i a dreamer?

  • HP 7110 all in one printer scanner, etc.

    My hp 7110 will scan and copy, but stopped printing yesterday.  When I try to print a document from outlook or word or a pdf file, the printer "starts", makes some noises, and then stops and all the lights on the "all in one" apparatus start to flick

  • Rss Feeds in flash

    I'm working with different flash movies for a client. she has several flash movies playing back to back as advertisement for different retailers. Now she wants me to add Rss Feeds for local weather on the flash movies. Now i never done this before an

  • Problem with paying Photoshop photography program.

    So I entered my details, all correct, and now i'm just stuck on the screen saying 'your payment is being processed'. Apparently it's been processing for over a hour... Not sure what to do as I don't want to refresh or close the page. Any help?

  • TestStand API: Set relative path

    Dear NI community! Could someone help, please, with the following - is there is some option to set file path to code modules, inside test sequence, to have relative, but not absolute path? I add programmatically code modules to sequence steps, but cu