Executing or Extracting files from JAR

Hello all,
I've written a small application that needs to be able to launch a help file (in the form *.chm*) from a menu bar. My question/problem is one of efficiency. In order to execute the *.chm* booklet I've written code that gets the files from within the JAR as an InputStream and writes it to a directory so it can be displayed. In order for the booklet to launch properly I have to write about 12 files (stylesheets and supporting scripts) to a directory; tedious and wasteful it seems. Since a JAR file is essentially a ZIP file, shouldn't I be able to extract the files to a directory without reading and writing each file individually? Can anyone direct/show me another method of doing this? Can I launch the files from within the JAR itself? The code I am using is as follows...
InputStream helpContent=this.getClass().getResourceAsStream("appContent.chm");
BufferedReader reader=new BufferedReader(new InputStreamReader(helpContent));
     try{
          BufferedWriter writer=new BufferedWriter(new FileWriter("helpContent.chm"));
          while(true){
               if(!reader.ready()){
                    break;
               writer.write(reader.readLine());
          writer.flush();
          writer.close();
          reader.close();
                }This snippet of code would inevitably be run/looped for each file necessary to achieve proper output.

The extraction is working properly now. I'm implementing code based on veldhanas suggests; thank you very much Veldhanas. At first the code was throwing a FileNotFoundException on the MANIFEST file. I found that it's because while cycling through as an enumeration it wasn't picking up on the fact that the MANIFEST lies in a subdirectory of the jar itself "META-INF. To solve this problem I create the subdirectory myself via
{code}
          File metaDir=new File("./META-INF");
          metaDir.mkdir();
{code}
The code I'm implementing is as follows...
{code}
          int jarReturnValue=jarChooser.showOpenDialog(null);
          if(jarReturnValue==JFileChooser.APPROVE_OPTION){
                    //get the selected file from chooser
               jarFile=jarChooser.getSelectedFile();
                    //display the file location
               System.out.println(jarFile.toString());
               File metaDir=new File("./META-INF");
               metaDir.mkdir();
               try{
                         //new instance of a jarfile object
                    jar=new JarFile(jarFile);
                    e=jar.entries();     //store the entries within an enumeration
                         //cycle through the jarfile elements as "Enum"
                    while(e.hasMoreElements()){
                         JarEntry innerFile=(JarEntry)e.nextElement();
                         System.out.println(innerFile.toString());
                         File outputFile=new File(destDir+File.separator+innerFile.toString());
                         System.out.println(outputFile.toString());
                              //if the inner which at current iteration is dir, make dir
                         if(innerFile.isDirectory()){
                              outputFile.mkdir();
                              continue;
                              //inputstream is the file within the zip/jar to read from
                         inputStream=jar.getInputStream(innerFile);
                              //fileoutput stream is the file to create outside of the jar
                         fileOutputStream=new FileOutputStream(outputFile);
                              //while there is information to be read
                         while(inputStream.available()>0){
                                   //write the contents of the inner file to the outter file
                              fileOutputStream.write(inputStream.read());
                         fileOutputStream.flush();
                         fileOutputStream.close();
                         inputStream.close();
               }catch(Exception ex){
                    ex.printStackTrace();
{code}
*PROBLEM SOLVED*: Thank you to everyone that invested time in this post and shared some useful knowledge. Your help has been very much appreciated!
Edited by: GooBeR81u812 on Dec 15, 2008 6:17 AM

Similar Messages

  • Extracting file from a TAR file with java.util.zip.* classes

    Is there a way to extract files from a .TAR file using the java.util.zip.* classes?
    I tried in some ways but I get the following error:
    java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.<init>(ZipFile.java127)
    at java.util.zip.ZipFile.<init>(ZipFile.java92)
    Thank you
    Giuseppe

    download the tar.jar from the above link and use the sample program below
    import com.ice.tar.*;
    import java.util.zip.GZIPInputStream;
    import java.io.*;
    public class untarFiles
         public static void main(String args[]){
              try{
              untar("c:/split/20040826172459.tar.gz",new File("c:/split/"));
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println(e.getMessage());
         private static void untar(String tarFileName, File dest)throws IOException{
              //assuming the file you pass in is not a dir
              dest.mkdir();     
              //create tar input stream from a .tar.gz file
              TarInputStream tin = new TarInputStream( new GZIPInputStream( new FileInputStream(new File(tarFileName))));
              //get the first entry in the archive
              TarEntry tarEntry = tin.getNextEntry();
              while (tarEntry != null){//create a file with the same name as the tarEntry  
                   File destPath = new File(
                   dest.toString() + File.separatorChar + tarEntry.getName());
                   if(tarEntry.isDirectory()){   
                        destPath.mkdir();
                   }else {          
                        FileOutputStream fout = new FileOutputStream(destPath);
                        tin.copyEntryContents(fout);
                        fout.close();
                   tarEntry = tin.getNextEntry();
              tin.close();
    }

  • "An error occurred while extracting files from the package "BaseSystem.pkg".

    Hello!
    I have a
    MacBookPro5,5
    Prozessortyp:Intel Core 2 Duo
    Prozessorgeschwindigkeit:2.26 GHz
    Anzahl der Prozessoren:1
    Gesamtzahl der Kerne:2
    L2-Cache:3 MB
    Speicher:2 GB
    Busgeschwindigkeit:1.07 GHz
    Boot-ROM-Version:MBP55.00AC.B03
    SMC-Version (System):1.47f2
    Hardware-UUID:A2DD27C4-9829-5A4D-854B-485EF8A6B20F
    Problem:
    I upgraded Leopard to Snow Leopard. Everything worked fine for a month. To free up disk space I deleted some of the iPhoto flders (modfied and original images). Everything worked still fine. Shut down the computer. Next day it was incredibly slow. At the same time the indexing was running. I stopped indexing, but stll slow. Every operation took minutes. I tried all the tricks that I found in the internet (repaired file permissions, repaired disk, cleared PRAM , moved big filed from desktop, etc.). After 24 full hours of trying all this I decided to erase the hard drive and reinstall, directly from the Snow Leopard Install disk, but it fails after downloading the packages. Below is the part of the log. Then I tried to use the old Leopard install DVD to reinstall Leopard, it then sais estimated time 12 hours or so and eventually crashed, spitting out a lot of "reportcrash" in the log. What is going on? I'm running out of options. Any advice? Would zeroing the hard drive help? If nothing else I plan to buy a new hard drive, since the only explanation I have is that there is a problem with the hard driven although the disk utility says it is OK. I need a bigger one anyway. Any ideas? Thank you!
    Aug 16 05:17:31 localhost OSInstaller[139]: IFPKInstallElement (191 packages)
    Aug 16 05:17:35 localhost OSInstaller[139]: PackageKit: ----- Begin install -----
    Aug 16 05:17:35 localhost OSInstaller[139]: PackageKit: request=PKInstallRequest <191 packages, destination=/Volumes/Macintosh HD>
    Aug 16 05:17:36 localhost OSInstaller[139]: PackageKit: Extracting /Volumes/Macintosh HD/Mac OS X Install Data/BaseSystem.pkg (destination=/Volumes/Macintosh HD/.OSInstallSandbox-tmp/Root, uid=0)
    Aug 16 05:31:59 localhost Unknown[80]: /SourceCache/AppleFSCompression/AppleFSCompression-24.0.1/Common/DataPool.c:116 : Error: finished pool without filling it
    Aug 16 05:31:59 localhost Unknown[80]: /SourceCache/AppleFSCompression/AppleFSCompression-24.0.1/Common/commonUtils.c: 315: Error: fh_pread -1
    Aug 16 05:31:59 localhost Unknown[80]: /SourceCache/AppleFSCompression/AppleFSCompression-24.0.1/Common/StreamCompress or.c:236: Error: write failed for /Volumes/Macintosh HD/.OSInstallSandbox-tmp/Root//System/Library/Frameworks/OpenCL.framework/Versi ons/A/Resources/runtime.amdil.bc: Invalid argument
    Aug 16 05:31:59 localhost Unknown[80]: /SourceCache/AppleFSCompression/AppleFSCompression-24.0.1/Common/StreamCompress or.c:260: Error: futimes failed for /Volumes/Macintosh HD/.OSInstallSandbox-tmp/Root//System/Library/Frameworks/OpenCL.framework/Versi ons/A/Resources/runtime.amdil.bc: Invalid argument
    Aug 16 05:31:59 localhost Unknown[80]: /SourceCache/AppleFSCompression/AppleFSCompression-24.0.1/Common/StreamCompress or.c:829: Error: returning errno 22 from FinishStreamCompressorQueue
    Aug 16 05:32:10 localhost OSInstaller[139]: PackageKit: Install Failed: PKG: extracting "com.apple.pkg.BaseSystem"\nError Domain=PKInstallErrorDomain Code=110 UserInfo=0x12c8366a0 "An error occurred while extracting files from the package “BaseSystem.pkg”." Underlying Error=(Error Domain=BOMCopierFatalError Code=22 UserInfo=0x12e703300 "The operation couldn’t be completed. FinishStreamCompressorQueue error") {\n    NSFilePath = "/Volumes/Macintosh HD/.OSInstallSandbox-tmp/Root";\n    NSLocalizedDescription = "An error occurred while extracting files from the package \U201cBaseSystem.pkg\U201d.";\n    NSURL = "BaseSystem.pkg -- file://localhost/Volumes/Macintosh%20HD/Mac%20OS%20X%20Install%20Data/index.pro duct";\n    NSUnderlyingError = "Error Domain=BOMCopierFatalError Code=22 UserInfo=0x12e703300 \"The operation couldn\U2019t be completed. FinishStreamCompressorQueue error\"";\n    PKInstallPackageIdentifier = "com.apple.pkg.BaseSystem";\n}
    Aug 16 05:32:10 localhost OSInstaller[139]: install:didFailWithError:Error Domain=PKInstallErrorDomain Code=110 UserInfo=0x12c8366a0 "An error occurred while extracting files from the package “BaseSystem.pkg”." Underlying Error=(Error Domain=BOMCopierFatalError Code=22 UserInfo=0x12e703300 "The operation couldn’t be completed. FinishStreamCompressorQueue error")
    Aug 16 05:32:11 localhost OSInstaller[139]: Install failed: Die Installation ist aufgrund eines Fehlers fehlgeschlagen. Wenden Sie sich an den Hersteller der Software.
    Aug 16 05:32:13 localhost OSInstaller[139]: Allowing machine sleep.
    Aug 16 05:32:15 localhost OSInstaller[139]: Memory statistics for 'Installation ist fehlgeschlagen' pane:
    Aug 16 05:32:15 localhost OSInstaller[139]: Physical Memory Allocation:   139 MB wired,   259 MB trapped,   397 MB active,     7 MB inactive,  1246 MB free,  1650 MB usable,  2048 MB total

    It sounds to me like your Internal Hard Drive is failing.
    I recommend you buy a new one, that is a good candidate for replacing the old one, but install it in an External enclosure and Install a fresh Mac OS X on it from the DVD. You can boot your Mac from any attached drive.
    The new System can be used to get some work done, check your emails, and takes the pressure off resolving this immediately. You can also attempt to salvage files off the old drive if needed.
    Once things seem to be working, then move the new drive inside the computer. Failures at this point may be due to bad cable, which has been a problem in some of these MacBooks.
    Use security erase, write Zeroes, one pass, to re-write every block on the old drive. Any block discovered to be bad will be replaced with spares the drive holds in reserve for this purpose. If more than 10 blocks are pared on one pass, "Initialization Failed!" will be the result. Although you can try the erase again, there is some question whether you want to trust this drive with your precious data.

  • Executing a .bat file from java code

    Im writing a utility and i need to be able to create and execute a .bat file from my program. I can create the .bat file fine but when i try to execute it nothing happens. I tried to use the following line of code to try to execute the .bat file (called make.bat) :
    try
    String parameterString = "\"C:\\WINNT\\System32\\cmd.exe\" C:\\ITS_Test\\make.bat";
    Runtime.getRuntime().exec(parameterString);
    catch (Exception e)
    System.out.println(e);
    The Runtime.getRuntime()exec() method worked fine when trying to execute an excel file but for some reason it dosen't want to work for the DOS prompt. Any ideas?

    Thanks everyone for all the replies.
    I have tried all the above with no luck. Im using netbeans, does anyone think that it could be a problem with the IDE.
    I tired the following code :
    String parameterString = "cmd.exe /C \"C:\\ITS_Test\\make.bat\"";
    Process pr = Runtime.getRuntime().exec(parameterString);
    pr.waitFor();
    This code does not throw any exceptions but just hangs. I also tried:
    String [] parameterString = {"cmd", "/c", "C:\\ITS_Test\\make.bat"};
    Process pr = Runtime.getRuntime().exec(parameterString);
    pr.waitFor();
    and:
    String parameterString = "\"C:\\WINNT\\System32\\cmd.exe\" \"C:\\ITS_Test\\make.bat\"";
    Process pr = Runtime.getRuntime().exec(parameterString);
    pr.waitFor();
    with the same result. Does anyone know why it just hangs and nothing happens (no exceptions thrown)?

  • How to execute a  .sql file from a batch file

    Hi all
    I've to take backup of a database weekly twice on every wednesday & Friday @ 5pm IST. I've written a hot backup script, which works every well.
    now i want to automate the script. ie i want this script to run on wednesday & friday @ 5pm without any human interfearance ie with out actually any1 executing this script.
    i created a batch file prod.bak with the following lines
    @echo off
    set oracle_sid=testdb
    set oracle_home=d:\oracle\ora92
    sqlplus /nolog
    connect sys as sysdba/oracletest@testdb
    this batch file when eexecuted connects me to sql prompt.
    Now i want to execute my backup script bkp.sql automatically when it is connected to sql prompt.
    (i tried with these lines in the above batch file...
    call bkp.sql---it just opens the bkp.sql file in notepad & displays the script
    start bkp.sql---same as call
    connect / as sysdba/pwd@[email protected] --- does not work simply remains a the sql prompt.
    At 17:00 /Every:w,f "d:\bkp.sql"---does not work simply remains at the sql promt.)
    Can any1 let me know what should i write in the batch file that will execute the bkp.sql file automatically after it gets connected to sql prompt. M using oracle 9i.
    I'll manage he time through windows utility of scheduling task.. Let me know how to execute the .sql file from a batch file.
    Thanks
    Tripti

    Try
    sqlplus "sys/oracletest as sysdba" @bpk.sql
    Working locally, and having set the ORACLE_SID, you don't need to specify the SqlNet alias (@testdb).
    Remember to put an exit at the end of the bpk.sql script.

  • How can I execute a  .bat  file from inside a java application

    I have a .bat file which contains an executable file(.exe) and some input and output file names. What commands can I use to execute this bat file from my java application.

    After raeding tkleisas' reply; i am trying to invoke another application (which can be invoked from the command line) by using a batch file and trying Runtime.exec for executing a batch file.
    My current code is:
    Runtime runtime = Runtime.getRuntime();
    Process trialProcess;
    trialProcess = runtime.exec("cmd.exe /C start C:\\guns.bat /B");
    And my guns.bat looks like:
    cd C:\CALPUFF
    echo trial
    start calpuff.exe CALPUFF.INP
    This is not working for me and i get the following in the error stream of the trialProcess:
    Error :
    The system cannot execute the specified program.
    Process finished with exit code 1
    Has anyone come across something like this and know what's wrong with this one??
    thnx

  • How to execute SQOOP.cmd file from SSIS execute process task?

    How to execute SQOOP.cmd file from SSIS execute process task?
    What is argument need to be prefixed in the arguments property
    Executable: C:\Hadoop\sqoop-1.4.2\bin\sqoop.cmd
    Arguments: /C "sqoop import -connect "jdbc:sqlserver://mysystem:1433;database=test;username=myuser;password=mypwd;" -table emp  -target-dir /user/emptable -m 1"
    Thanks
    Durga

    Hi Durga,
    SQOOP.cmd must be no different than any other .cmd/.bat I assume, your question is more about setting the parameters up I guessed.
    So unless the arguments change dynamically you can call SQOOP.cmd from yet another .cmd that has its parameters passed to it and the former you simply set to run without the arguments in Execute Process Task.
    Otherwise, in general to set a bat/cmd file to run in SSIS one needs to do this:
    PS: It is a good idea to populate the working directory with the path to the .cmd
    Arthur My Blog

  • Hi this message appears after 2 hours downloading Mavericks : an error occurred while extracting files from the package "mzps4135638417199433253.pkg"

    Hi this message appears after 2 hours downloading Mavericks in App Store :
    an error occurred while extracting files from the package "mzps4135638417199433253.pkg"
    Same with "CMD + R"
    Help...

    It sounds to me like your Internal Hard Drive is failing.
    I recommend you buy a new one, that is a good candidate for replacing the old one, but install it in an External enclosure and Install a fresh Mac OS X on it from the DVD. You can boot your Mac from any attached drive.
    The new System can be used to get some work done, check your emails, and takes the pressure off resolving this immediately. You can also attempt to salvage files off the old drive if needed.
    Once things seem to be working, then move the new drive inside the computer. Failures at this point may be due to bad cable, which has been a problem in some of these MacBooks.
    Use security erase, write Zeroes, one pass, to re-write every block on the old drive. Any block discovered to be bad will be replaced with spares the drive holds in reserve for this purpose. If more than 10 blocks are pared on one pass, "Initialization Failed!" will be the result. Although you can try the erase again, there is some question whether you want to trust this drive with your precious data.

  • Extracting files from Portfolio - problem with outlook email created portfolios

    Currently I have developed a plugin that can extract files from portfolios using:-
    PDNameTree tree = PDDocGetNameTree(pdDoc, ASAtomFromString("EmbeddedFiles"));
    and
    PDFileAttachmentFromCosObj
    But i've noticed with Outlook email created portfolios the above is PDNameTree invalid.  any suggestions?   is it under another atom string or something?
    Thanks,
    Lee.

    ok, found something out here... if I close the doc using AVDocClose then re-open in the code using PDDocOpen then the PDNameTree tree = PDDocGetNameTree(pdDoc, ASAtomFromString("EmbeddedFiles"));  works!!!
    but now I have a problem getting the original pdf open filename.
    usually can get it with below code but it's returning the Folder path + garbage instead. (this only happens with portfolios created by outlook that I have tested)
    There must be a better way of doing this, any ideas? thanks, lee.
    ASFile asFile = PDDocGetFile(pdDoc);
    ASPathName asPathName = ASFileAcquirePathName(asFile);
    char* temp = ASFileSysDIPathFromPath(ASGetDefaultFileSys(), asPathName, NULL);

  • Execute a .cmd file from Java program on tomcat which is running as service

    I have a .cmd/,.bat file which has to be executed depending on the parameters I pass through JSP page hosted on a tomcat instance.
    Tomcat is running as a windows service.
    I need my .cmd file to be opened in a cmd or DOS box so that user can interact with the dos window, which is mandatory.
    When I run the program from eclipse it works well but on the tomcat , the server side the output of the command is written to my log file and it gives no chance for users to monitor and interact with the command.
    Should I do something with log4j settings or is due to tomcat running as service?
    Please help.
    thanks

    thanks for the responses.
    But the design is like that.Then it needs to be fixed.
    I think this is why there's a shortage of people to write computer applications, they are all wasting their time struggling to implement bad designs.
    its a scheduler to be run on tomcat where we interact
    with the running batch files and can't be changed.A scheduler in Tomcat? Why run a scheduler in an application server?
    any help is appreciated.
    I tried to execute the batch file from servlet it
    runs , but i see the cmd.exe in windows task manager
    and need a dos box open.
    Any ideas?If you need a DOS box open then you need a signed-on user. So here's my patch:
    1. Write an application that listens for messages from this Tomcat scheduler, and when it receives those messages it does something in a DOS box.
    2. Have somebody sign on to the server and run that application.
    3. Change the Tomcat scheduler to send messages to that application instead of trying to actually run it.
    It's up to you what kind of messages you should send. There are plenty of choices.

  • Extracting file from oracle repository from  a shell

    Hi all,
    I have to extract file from a SCM configuration in a Unix AIX environment using a shell.
    I can't use command line tool because I'm in a unix environment (Right?).
    Is possible I think using scm api but I don't find any usefull example

    Close your question here and open here
    Oracle Discussion Forums » Oracle Database » Application Express

  • Tried to install OS X Yosemite on my MacBook. Got message that it could not be installed on my computer due to error while extracting files from package "Essentials.pkg". When i quit the installer as recommended it goes in a loop and gets stuck.

    Tried to install OS X Yosemite on my MacBook. Got message that it could not be installed on my computer due to error while extracting files from package "Essentials.pkg". When i quit the installer as recommended it goes in a loop and gets stuck.

    Hey corrafromlondon,
    Thanks for the question. After reviewing your post, it sounds like the installer file isn't working. Have you tried deleting the installer and redownloading the installer? I would recommend that you read this article, it may be able to help you isolate or resolve the issue.
    How to install OS X Yosemite on your Mac - Apple Support
    you can find the Yosemite installer app in your Applications folder or Launchpad. 
    Thanks for using Apple Support Communities.
    Have a nice day,
    Mario

  • Need help, executing a SQL file from Forms

    Hi everyone,
    I don't know if this can be done. I want to execute a SQL file from a When-Button-Pressed trigger. I checked a couple of place but havent found anything yet on how to do this. If someone know of a way, please help.
    Thanks
    Eric

    procedure p_call_sqlplus is
       l_filename varchar2 (1000) := 'C:\abc\def\test.sql'  ;
    begin
       host ('sqlplus /NOLOG @' ||  l_filename ) ;
    end ;
    rem ======== test.sql ========
    connect scott/tiger
    spool 'C:\abc\def\test'
    select * from emp ;
    spool off
    exit
    rem ======================working on the machine where forms is running

  • Extracting files from executable jars at runtime

    I'm still pretty new to Java, and I'm trying to find out how (if it's possible) to access files inside jars at runtime. More to the point, I am trying to make a help file for my application, stored as a .txt file. Currently I have the text file in the same directory as the source code, and I am bundling the source directory into an executable jar. However, when the jar is executed, it cannot find the file. There's got to be some mechanism for automatically loading files that are in the source directory. This issue is confused by the fact that I am using Windows XP, and so the default home directory to execute from is the My Programs directory. Any help would be appreciated!

    [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html]Class.[url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)]getResourceAsStream(java.lang.String) is what ye want.
    InputStream is = class.getResourceAsStream("myhelpfile.txt"); will get a file in the folder as your class file.
    InputStream is = class.getResourceAsStream("/myhelpfile.txt"); will get a file in the root of the jar.

  • Java.io.filepermission error while executing a batch file from java prog

    Hi,
    i want run a java program which executes a batch file, both are in a jar file. while am trying this using webstart it shows error:access denied java.io.filepermission <<ALL FILES>>execute. why this happens how to rectify this.
    By
    Vinod

    Clearly, it would be a security vulnerability to be able to do such a thing from the web w/o user granting trust to the application.
    Java Web Start applications run in the Java SE secure sandbox unless they have been granted all-permissions by the user:
    1.) sign all jar files.
    2.) add <security><all-permissions/></security> to the jnlp file.
    The user would then be prompted to grant trust to the applications.
    /Andy

Maybe you are looking for

  • Can't view Photos on my Nano

    Hi guys, i got following problem. i got an ipod nano (2nd generation & 8gb, i want to put some photos on it, 7 images (jpeg,bitmap & gif) about 1mb. so i created a folder and put these 7 photos in it, then i have chosen that folder wit iTunes and evr

  • XI3 SOAP sender and Receiver

    Hi I am stuck with a connecting to scenarios using SOAP channel. In short there is one business scenario that based on some conditions must start other scenarios (each one built around one business process). I am trying to send asynchronous SOAP mess

  • Trying to understand oci8 refcursor bits

    Hi I have been using ADOdb for a while and sort of not thinking too much about it, but sort of trying to get some of the stuff. Perhaps I think too much like my old C programming daze and wonder about things that I should not. With that in mind I was

  • CSV file column heading

    Hi Experts, This is File to IDOC scenario. The source file is a csv file with header and item records. The file comes with column headings and now problem is how to remove the column headings using my content conversion. Any help would be appericiate

  • Change data capture - ignore delete?

    Hello, I'm trying to solve an issue I met on a synchronous change data capture : I created a CDC table with the DBMS_LOGMNR_CDC_PUBLISH.CREATE_CHANGE_TABLE procedure: BEGIN    DBMS_LOGMNR_CDC_PUBLISH.CREATE_CHANGE_TABLE (       OWNER             => '