Append to jar file using java codings

Hi,
I have codings which could create jar file and write datas in it. but i need to append datas to existing jar file using java codings.Here i have attached my codings which will write datas to new jar file. when ever i use this my existing contents gets overritten. wat can i add to this to append.
FileOutputStream stream = new FileOutputStream(archiveFile,true);// archive file is jar file name
     JarOutputStream out = new JarOutputStream(stream, new Manifest());
JarEntry jarAdd = new JarEntry(tobeJar.getName()); // tobejar is a file to write in jar.
jarAdd.setTime(tobeJar.lastModified());
               out.putNextEntry(jarAdd);
               // Write file to archive
               FileInputStream in = new FileInputStream(tobeJar);
               while (true) {
               int nRead = in.read(buffer, 0, buffer.length);
               if (nRead <= 0)
               break;
               out.write(buffer, 0, nRead);
               out.closeEntry();
out.close();

JarInputStream in = new JarInputStream(new FileInputStream(oldJarName), true); // oldJarName is the JAR that contains all the files we want to keep
JarOutputStream out = new JarOutputStream(new FileOutputStream(tempJarName)); // this is your "out" variable
// copy the files from the old JAR to the new, but don't close the new JAR yet
JarEntry inEnt;
while ((inEnt = in.getNextJarEntry()) != null) {
  JarEntry outEnt = new JarEntry(inEnt); // copy size, modification time etc.
  byte[] data = inEnt.getSize();
  in.read(data); // read data for this old entry
  in.closeEntry();
  out.putNextEntry(outEnt);
  out.write(data); // copy it to the new entry
  out.closeEntry();
// now write an entry for the file we want to append - this is the OP's code
JarEntry jarAdd = new JarEntry(tobeJar.getName()); // tobejar is a file to write in jar.
jarAdd.setTime(tobeJar.lastModified());
out.putNextEntry(jarAdd);
// Write file to archive
FileInputStream in = new FileInputStream(tobeJar);
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
out.closeEntry();
// and *now* we close the new JAR file.
out.close();
// We then delete the old JAR file...
new File(oldJarName).delete();
// ... and rename the new JAR file to use the old one's name.
new File(tempJarName).renameTo(new File(oldJarName));

Similar Messages

  • How to run .jar on linux & how to create .jar file using java?

    hi, may i know how to run .jar on linux & how to create .jar file using java? Can u provide the steps on doing it.
    thanks in advance.

    Look at the manual page for jar:
    # man jar
    Also you can run them by doing:
    # java -jar Prog.jar

  • How to record .jar file using Java Protocol

    Hi,
    I Tried to record .jar using Java protocol by using HR Loadrunner 11.0 Version tool.
    Am unable to record the application.
    Can any one suggest me the process of recording .jar file using load runner?
    Thanks,
    Venkat

    Look at the manual page for jar:
    # man jar
    Also you can run them by doing:
    # java -jar Prog.jar

  • Problem in Creating a jar file using java.util.jar and deploying in jboss 4

    Dear Techies,
    I am facing this peculiar problem. I am creating a jar file programmatically using java.util.jar api. The jar file is created but Jboss AS is unable to deploy this jar file. I have also tested that my created jar file contains the same files. When I create a jar file from the command using jar -cvf command, Jboss is able to deploy. I am sending the code , please review it and let me know the problem. I badly require your help. I am unable to proceeed in this regard. Please help me.
    package com.rrs.corona.solutionsacceleratorstudio.solutionadapter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.jar.JarEntry;
    import java.util.jar.JarOutputStream;
    import java.util.jar.Manifest;
    import com.rrs.corona.solutionsacceleratorstudio.SASConstants;
    * @author Piku Mishra
    public class JarCreation
         * File object
         File file;
         * JarOutputStream object to create a jar file
         JarOutputStream jarOutput ;
         * File of the generated jar file
         String jarFileName = "rrs.jar";
         *To create a Manifest.mf file
         Manifest manifest = null;
         //Attributes atr = null;
         * Default Constructor to specify the path and
         * name of the jar file
         * @param destnPath of type String denoting the path of the generated jar file
         public JarCreation(String destnPath)
         {//This constructor initializes the destination path and file name of the jar file
              try
                   manifest = new Manifest();
                   jarOutput = new JarOutputStream(new FileOutputStream(destnPath+"/"+jarFileName),manifest);
              catch(Exception e)
                   e.printStackTrace();
         public JarCreation()
         * This method is used to obtain the list of files present in a
         * directory
         * @param path of type String specifying the path of directory containing the files
         * @return the list of files from a particular directory
         public File[] getFiles(String path)
         {//This method is used to obtain the list of files in a directory
              try
                   file = new File(path);
              catch(Exception e)
                   e.printStackTrace();
              return file.listFiles();
         * This method is used to create a jar file from a directory
         * @param path of type String specifying the directory to make jar
         public void createJar(String path)
         {//This method is used to create a jar file from
              // a directory. If the directory contains several nested directory
              //it will work.
              try
                   byte[] buff = new byte[2048];
                   File[] fileList = getFiles(path);
                   for(int i=0;i<fileList.length;i++)
                        if(fileList.isDirectory())
                             createJar(fileList[i].getAbsolutePath());//Recusive method to get the files
                        else
                             FileInputStream fin = new FileInputStream(fileList[i]);
                             String temp = fileList[i].getAbsolutePath();
                             String subTemp = temp.substring(temp.indexOf("bin")+4,temp.length());
    //                         System.out.println( subTemp+":"+fin.getChannel().size());
                             jarOutput.putNextEntry(new JarEntry(subTemp));
                             int len ;
                             while((len=fin.read(buff))>0)
                                  jarOutput.write(buff,0,len);
                             fin.close();
              catch( Exception e )
                   e.printStackTrace();
         * Method used to close the object for JarOutputStream
         public void close()
         {//This method is used to close the
              //JarOutputStream
              try
                   jarOutput.flush();
                   jarOutput.close();
              catch(Exception e)
                   e.printStackTrace();
         public static void main( String[] args )
              JarCreation jarCreate = new JarCreation("destnation path where jar file will be created /");
              jarCreate.createJar("put your source directory");
              jarCreate.close();

    Hi,
    I have gone through your code and the problem is that when you create jar it takes a complete path address (which is called using getAbsolutePath ) (when you extract you see the path; C:\..\...\..\ )
    You need to truncate this complete path and take only the path address where your files are stored and the problem must be solved.

  • How to run a jar file using Java application.

    Hi all,
    I know that jar file can run using the following command, using the command prompt.
    java -jar jar-fileBut I don't know how to run that command through a Java code. Hope it's clear to you.
    So can you please explain how can I do it.
    Thanks,
    itsjava

    rayon.m wrote:
    The solution given by ropp appears to have nothing to do with what you asked about.Ok sir, I got the point.
    I've try a test as follows. But it doesn't give any output. Even not an exception.
            try {
                String[] temp = new String[]{"java", " -jar", " MainApp.jar"};
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(temp);
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);
                System.out.println("Temp_Values");
            catch(InterruptedException ex) {
                System.out.println(ex.getMessage());
            catch (IOException ex) {
                System.out.println(ex.getMessage());
            }I've debug and see, but the exitValue is even not exist at run time. Can you tell me where I'm going wrong.

  • Making Executable Jar file using java Application

    Following Program creates the jar file at specified location. but, I wonder why this file does not execute on double clicking on it, in spite of that the Manifest file contain correct main class file name
    //MakJar.java
    import java.io.*;
    public class MakJar
    public static void main(String[] args)throws IOException{
    Process p;
    String str="D:\\Himesh\\JFiles";
    try {
    BufferedWriter out = new BufferedWriter(new FileWriter(str+"\\mainClass.txt"));
    out.write("Main-Class: TestFrame\n");
    out.close();
    } catch (IOException e) {
    try
         p=Runtime.getRuntime().exec("cmd /c D:\\Java6\\jdk1.6.0\\bin\\javac.exe "+str+"\\TestFrame.java");
         p=Runtime.getRuntime().exec("cmd /c D:\\Java6\\jdk1.6.0\\bin\\jar cvmf "+str+"\\mainClass.txt "+str+"\\Demo.jar "+str+"\\*.class");
    catch(IOException e)
    System.err.println("Error on exec() method");
    e.printStackTrace();
    }

    Sir,
    On execute the jar using a "java -jar. . ." command. it gives the error--
    "Exception in thread "main" java.lang.NoClassDefFoundError : TestFrame"
    On Extracting the files from jar file made by the java program,i found that the manifist file ( containing the name of main class) and t the class file are included in the jar file.
    But if I make the jar file manually it works perfectly.I have even reinstalled the java but the problem persists
    Same thing happen if i use MS-DOS batch file.
    ??????If i put the batch file in the same directory and execute it The resulting jar file works,But
    ??????if the batch file is executed from outside the directory The resulting jar file fails execute.
    what should i do???

  • Modifying JAR file using java.util.jar package  over the network

    Hello,
    I am modifying a JAR file programmatically using java.util.jar package. The time taken to save the contents to a local disk is very less (around 1 sec) . When I tried modifying the JAR from a remote machine over the network (from mapped drive or shared folder of WIN NT), the time taken to save is 15-20 times more.
    I am recreating the whole JAR while modifying. Is there any way to improve the performance. Or is it possible to write only the changed files?
    Thanks,
    Prasad Y S.

    When you "update" a jar file, you must always recreate it from scratch.

  • Create BPEL jar file using Bpelc via Java classes

    HI,
    I am trying to create the BPEL files ( xyz.bpel, bpel.xml, xyz.wsdl etc.. ) on the fly using Java code... Once I create all these files, I create a packaged jar (Ex : bpel_xyz_v2006_10_17__37256.jar) file and deploy the same in the Bpel PM.
    Right now, in order to create the jar file, I am running the bpelc.bat file under bpel/bin and then using the IBPELDomainHandle, I am deploying the process.
    But my requirement is to create the jar file using java rather than executing the bpelc.bat file..
    Can you please give me pointers as to how to achieve the same?
    Thanks
    Pramod

    Actually, I had figured out the part of calling the Bpelc class, but initially I was trying to create an object of the class and was not able to do so. That was where I got stuck.
    Eventually, I did something like the code snippet below and it works fine and the jar file is created. Just fyi for anyone looking in the future.
    String[] setupValues;
    setupValues = new String[]{ "-home", "D:\\product\\10.1.3.1\\OracleAS_1\\bpel", "-rev",
    "1.0", };
    Bpelc.main(setupValues);
    Thanks
    Pramod

  • How can i rename a jar file using only java code

    i have tried everything i can think of to accomplish this but nothing works.

    ghostbust555 wrote:
    In case you geniuses haven't realized I said I tried everything I can think of not that I tried everything. So help or shut up I realize that I didn't try everything but if you can't figure it out either DO NOT POST.
    And the question is how can i rename a jar file using java code? As it says in the title. Read.I would tell you to use the File.renameTo method, but surely that would have been obvious, and you would have tried it already? But maybe you didn't. You were kind of lacking in details in what you tried.
    And yes, I am a genius. Just don't confuse "genius" with "mind-reader".

  • Adding jar file in my gerareted jar file using netbean 4.0

    Hi,
    I write an application de process XML file using JDOM. I add the JDom package jar file to my project and everything work fine. But when I generate, my project jar file using netbean 4.0, my generated jar, is not working with the XML files anymore. Everything seems like it didn't include the JDOM jar file?
    Thanks for any help to fix the problem.

    I find that you can not use command-line such as java -classpath add classpath
    it can not work, I use netBeans4.0 i don't whether because of netbeans or java itself.
    you can add classpath in jar's Manifest.mf file
    Manifest-Version: 1.0
    Ant-Version: Apache Ant 1.6.2
    Created-By: 1.5.0_01-b08 (Sun Microsystems Inc.)
    Main-Class: chat.Main
    // add this line
    Class-Path: dir\*.jar //(jar file name)
    X-COMMENT: Main-Class will be added automatically by build

  • How to run test cases in a jar file using junit?

    Hi,
    I want to run test cases in a jar file using junit and the jar file is not in the class path. I wrote the following code, but it does not work.
    import java.net.URL;
    import java.net.URLClassLoader;
    import junit.framework.TestResult;
    import junit.textui.TestRunner;
    public class MyTestRunner {
         public static void main(String[] args) throws Exception{
              URL url = new URL("file:///d:/case.jar");
              URLClassLoader loader = new URLClassLoader(new URL[]{url});
              loader.loadClass("TestCase1");
              TestRunner runner = new TestRunner();
              TestResult result = runner.start(new String[]{"TestCase1"});
              System.out.println(result.toString());
    }Any ideas?
    Thanks a lot.

    Wouldn't it just be easier to put it on the classpath? You're trying to, anyway, with a URLClassLoader, albeit in an entirely unnecessarily complicated way

  • How can zip file using java ?

    I would like to ask is that any package or example code allowing zipping serveral file using java ?

    Here's a test program I wrote, which may help. As far as I know the jip/zar classes are interchangeable.
    import java.io.*;
    import java.util.jar.*;
    public class ZipTest
        public static void main(String[] args) throws Exception
            /* create a file stream for the new zip file */
            FileOutputStream fileOutputStream=new FileOutputStream("test.zip");
            JarOutputStream zipOutputStream=new JarOutputStream(fileOutputStream);
            /* open file to add to zip file */
            File file=new File("test.dat");
            FileInputStream fileInputStream=new FileInputStream(file);
            /* create a buffer and read file into buffer */
            int length=(int)file.length();
            byte[] buffer=new byte[length];
            fileInputStream.read(buffer,0,length);
            /* create entry in zip file */
            JarEntry jarEntry=new JarEntry("test.dat");
            /* add it */
            zipOutputStream.putNextEntry(jarEntry);
            zipOutputStream.write(buffer,0,length);
            /* clean up and exit */
            fileInputStream.close();
            zipOutputStream.close();
    }

  • Making jar files using API

    hello!
    I m trying to make a jar file using the API. When the jar tool is used for the same manifest file, it is correctly written and an executable jar is created. When I use the API, the jar file is made but it is nor executable. Here is that part of code:
    jar = new File(parent, jarName);
    System.out.println("Executing jar command...");
    //create jar file here
    Manifest mf = new Manifest(new FileInputStream(manifest));
    fos = new FileOutputStream(jar);
    jos = new JarOutputStream(new BufferedOutputStream(fos), mf);
    BufferedInputStream reader = null;
    byte[] data = new byte[BUFFER];
    int byteCount = 0;
    for(int i = 0; i < fileNames.length; i++)
    System.out.println("Adding " + fileNames);
    FileInputStream fis = new FileInputStream(fileNames);
    reader = new BufferedInputStream(fis, BUFFER);
    JarEntry entry = new JarEntry(new ZipEntry(fileNames));
    jos.putNextEntry(entry);
    while((byteCount = reader.read(data,0,BUFFER)) != -1)
    jos.write(data, 0, byteCount);
    }//end while
    reader.close();
    }//end for
    jos.close();//close jar output stream
    fos.close();
    I m sure someone will be kind and intelligent enough to solve the problem. Thank you!
    Umer

    A jar file is simply a Zip file. So the two API's are quite similar. First, you create a CRC - that is a way to make sure that the file isn't corrupted and that all the bytes are there (it's a polynominal algorithm that returns a number which is written in the Zip(Jar) file as well). Each entry is a file or directory. Before writing any data to the Zip(Jar) file, you have to write info on the actual file (like name, path, length etc). That's why you use putNextEntry(). Each file can have it's storing methods, although the most common is to use the "default" methods (built in the ZipOutputStream/JarOutputStream)
    But in this example you set the storing methods on the entry. You use the setMethod() method to switch between either storing or compression (don't know why, but in this example you don't compress the file - you should). I myself don't use the setSize() and setCompressedSize() methods at all (and it works fine). Don't know exactly what are the implications of using them. Neither do I use the setCrc() method (If I think a little, I've only used this API once - I don't use it that much), but it's quite straightforward. It's used to check that the data is ok, and since the CRC number is the result of an algorithm, it needs to know the bytes of UNCOMPRESSED data: that's why you use crc.update() on the bytes. After that you actually write all the info set before to the Zip (Jar) file using putNextEntry(). But remember that a ZipEntry doesn't have any data. You'll have to write it yourself: thus the need for the write method: Here are two small programs I used for Zipping and Unzipping. Changing them to work for Jar files is extremely simple:
    //Zip.java
    import java.io.*;
    import java.util.zip.*;
    public class Zip
         public static void main(String[] arg)
              try
                   if (arg.length < 3)
                        System.out.println("Usage: java Zip <0-9> <zip file> <file 1> [file 2] [file 3] ...");
                        System.exit(0);
                   System.out.println("Compressing files into file " + arg[1]);
                   ZipOutputStream out = null;
                   try
                        out = new ZipOutputStream(new FileOutputStream(arg[1]));
                   catch (FileNotFoundException ex)
                        System.out.println("Cannot create file " + arg[1]);
                        System.exit(1);
                   try
                        out.setLevel(Integer.parseInt(arg[0]));
                   catch (IllegalArgumentException ex)
                        System.out.println("Illegal compression level");
                        new File(arg[1]).delete();
                        System.exit(1);
                   for (int i=2; i<arg.length; i++)
                        System.out.println("\tCompressing file " + (i-1));
                        FileInputStream read = null;
                        try
                             read = new FileInputStream(arg);
                        catch (FileNotFoundException ex)
                             System.out.println("\tCannot find file " + arg[i]);
                             continue;
                        out.putNextEntry(new ZipEntry(arg[i]));
                        int av = 0;
                        while ((av = read.available()) != 0)
                             byte[] b = new byte[av < 64 ? av : 64];
                             read.read(b);
                             out.write(b);
                        out.closeEntry();
                        read.close();
                        System.out.println("\tDone compressing file " + i);
                   System.out.println("Done compressing");
                   out.finish();
                   out.close();
              catch (Exception e)
                   new File(arg[1]).delete();
                   e.printStackTrace(System.err);
    And the unzipping app:
    //UnZip.java
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    public class UnZip
         public static void main(String[] arg)
              try
                   if (arg.length < 1)
                        System.out.println("Usage: java UnZip <zip file> [to dir]");
                        System.exit(0);
                   String dir = "";
                   if (arg.length > 1)
                        dir = arg[1] + System.getProperty("file.separator");
                        File f = new File(arg[1]);
                        if (!f.exists()) f.mkdirs();
                   System.out.println("Decompressing files from file " + arg[0]);
                   ZipFile read = null;
                   try
                        read = new ZipFile(arg[0]);
                   catch (ZipException ex)
                        System.err.println("Zip error when reading file " + arg[0]);
                        System.exit(1);
                   catch (IOException ex)
                        System.err.println("I/O Exception when reading file " + arg[0]);
                        System.exit(1);
                   Enumeration en = read.entries();
                   while (en.hasMoreElements())
                        ZipEntry entry = (ZipEntry) en.nextElement();
                        System.out.println("\tDecompressing file " + entry.getName());
                        FileOutputStream out;
                        try
                             out = new FileOutputStream(dir + entry.getName());
                        catch (FileNotFoundException ex)
                             System.err.println("\tCannot write down to file " + dir + entry.getName());
                             continue;
                        InputStream re = read.getInputStream(entry);
                        int nRead = 0;
                        for (byte[] buffer = new byte[1024]; (nRead = re.read(buffer)) != -1; out.write(buffer, 0, nRead));
                        out.close();
                        System.out.println("\tDone decompressing file " + entry.getName());
                   read.close();
                   System.out.println("Done decompressing files");
              catch (Exception e)
                   new File(arg[1]).delete();
                   e.printStackTrace(System.err);

  • Writing into a jar file through Java program

    Is there a way to get a file from a jar (for ex. a properties file) make changes to it on the fly and write the same file back to the jar through a Java program?

    I cannnot give u exact code as i am bit busy..but i am giving close to exact
    below is code for reading contents of jar file
    import java.io.*;
    import java.util.jar.*;
    public class JarRead {
    public static void main (String args[])
    throws IOException {
    if (args.length != 2) {
    System.out.println(
    "Please provide a JAR filename and file to read");
    System.exit(-1);
    JarFile jarFile = new JarFile(args[0]);
    JarEntry entry = jarFile.getJarEntry(args[1]);
    InputStream input = jarFile.getInputStream(entry);
    process(input);
    jarFile.close();
    private static void process(InputStream input)
    throws IOException {
    InputStreamReader isr =
    new InputStreamReader(input);
    BufferedReader reader = new BufferedReader(isr);
    String line;
    while ((line = reader.readLine()) != null) {
    System.out.println(line);
    reader.close();
    now here say u have test.jar which contains test.txt (file)
    then
    java JarRead test.jar test.txt
    will print content of text.txt
    now in ur case u write content of each file in some other file modify it there and then create a jar file from those files using jaroutput stream .....
    this may not be all clear ..but what to do..bit busy...u are welcomed to make changes in above stratergy....n queries if any after using above stratergy and/or your great brain...

  • How to access the database jar file using the derby 10.2.1.6 database ?

    Hi,
    How to access the database jar file using the derby 10.2.1.6 database ?
    I have used like below. And i am getting the following the error:
    "org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'org.apache.derby.jdbc.EmbeddedDriver'
    at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1136)"
    My context.xml file looks like this:
    <Context crossContext="true">
    <Resource name="jdbc/derby" auth="Container"
    type="javax.sql.DataSource" driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
    url="jdbc:derby:jar(\CalypsoDemo\database.jar)samples"
    username="xxx" password="xxx" maxActive="20" maxIdle="10"
    maxWait="-1"/>
    </Context>
    What could be the reason.?
    Any suggestions will be appriciated.
    Thanks in Advance,
    Gana.

    ya, I have restarted. Can you please tell me whether the path which i am giving is right or not in the context file?
    Thanks,
    Gana.

Maybe you are looking for

  • Place multiple columns (from a word doc) in a document?

    Hello, I am trying to place a word document with three columns of text in an indesign document. I tried changing the settings to "three columns" but that didn't help, the document shows up as one long column that of course runs off the bottom of the

  • MrMP in regard to Lollipop

       Have read some of your earlier post you make excellent points and glad to see you speak up. I've worked extensively will computer hardware replacement, installing operating systems, drivers, etc. along with multimedia since 1998. And have particip

  • How to delete a software component in the IR

    I imported a software component from the SLD to the IR. Now I want to delete it. I can delete it in the SLD. But how can I get rid of it in my IR. The software component is empty.

  • BPFu00B4s dont open schedules, reports or packages in Client

    Hi experts, I am using BPC 7.0 SP 4 Microsoft Version and Microsoft Excel 2003. I have this problem, we created some BPF´s conected by Desktop Remote Connection to one virtual machine. And they work perfectly, but when i try to open this BPF´s using

  • Installing NWDI on CE

    HI, We are trying to setup NWDI for CE 7.1. When we go through the documents, we understand that we need to setup NWDI in a separate NW 7.0 server and use in CE environment. Cant we install NWDI on CE itself instead of installing in NW7.0 server. Oth