Run from within JAR

I have a java program which runs an external executable. I would like to include this executable in my jar file and have my program be able to find it. Basically I want to be able to say: java -jar MyProgram.jar and not have to have the external executable outside of the jar.
I've tried just putting the exe in the jar, but that doens't seem to be doing the trick. Any ideas?
Thanks.

runs an external executableI assume that you are using Runtime exec() to run the program.
Does your OS know how to find and execute a program that is within a jar file? If it has a syntax for that, then use that syntax. Otherwise you need to have the executable where the OS can find it. On some PATH.

Similar Messages

  • Can I get jar version from class run from within jar ?

    I am launching a number of applets from a single jar file. I want to display jar file version on initial applet. I would ideally like the applet to be able to determine from the jar file which it was part of what version it is . Is this possible ?
    Applets are swing based & I'm using java plugin

    if your jar file has a manifest that specifies the version number, you can use java.util.jar.JarFile to get the information. Other wise, you would just have to induce it based upon the file attributes of the jar file, using java.io. Remember that applets can not, by default, read the local file system, so you might have to use signed applets.

  • How to force SequenceFi​leUnload callback to run from within operator interface

    I need to force SequenceFileUnload callback to run from within operator interface arbitrary, with possibility to control execution flow.
    I.e. discarding object handle of execution object, which has client sequence file, which has SequenceFileUnload callback, causes it(SequenceFileUnload callback) to run. Unfortunately, after discarding execution object handle, it can be used to control execution flow(pausing, aborting, terminating).

    Thanks for the clarification. Here are the answers to your 3 questions:
    1) You can programmatically run any sequence (including callbacks) by using the TestStand API Engine.NewExecution() method.
    2) The Execution API object has several control methods for breaking, aborting, terminating, restarting, etc... All you need to do is obtain a reference to the Execution you want to perform one of these actions on and call the appropriate method on the reference. If you start the SequenceFileUnload callback with the Engine.NewExecution method, this returns a reference to the Execution object that you can call these methods on. If you don't use the NewExecution method, you can do a check in your UIMsg event handler for the StartExecution UIMsg event
    for an execution starting that is running the SequenceFileUnload callback, and simply manipulate the Execution reference the UIMsg contains as you see fit.
    3) To disable the SequenceFileUnload callback for a sequence file that is currently loaded. You can set the SequenceFile API object property "UnloadCallbackEnabled" to FALSE, and the callback will not execute for that file when it is unloaded unless you go back and reset the property to true before unloading. Note this property is reset each time you load the file.
    For more information on the TestStand API objects, methods, and properties discussed in this post, refer to the TestStand Programmer Help accessed through the Sequence Editor's Help >> TestStand Programmer Help menu selection.
    Jason F.
    Applications Engineer
    National Instruments
    www.ni.com/ask

  • Crystal report parameters not available when running from within SAP B1

    Hi
    I have found this problem a few times already and I think it is now about time I find a solution for it.
    On my latest Crystal report, I have 2 parameters.
    The 1e is a dynamic parameter, allowing the user to select multiple groups.
    The 2nd is also a dynamic parameter, allowing the user to select only a single item.
    These parameters works fine in Crystal and do what they are supposed to do.
    After publishing the report in SAP Busines One (SBO) and viewing it from within SBO, the 2 parameter prompts are still there but without the dynamic list to select any data from.
    On a previous report where a parameter has been defined as "Any value can be entered for the parameter" once again worked fine in crystal but from within SBO the parameter allowed no value to be entered.
    Have anyone got a solution for this.
    Regards
    Burger

    Sorry guys
    You have lost me. I have searched the form and I have worked through the whole pdf you suggested.
    I have no idea what I am supposed to do or see or use "ItemGroup@ SELECT ItmsGrpCod, ItmsGrpNam FROM OITB ORDER BY ItmsGrpCod"
    As a test I created a test report with the following parameters to test how it would present itself in B1
    1.     A static parameter with no list. Allow custom Values = True, Allow Multiple Values = True u2013 B1 result. A box that I could enter anything. Defeating the object as I wanted a list of valid options
    2.     A static parameter with no list. Allow custom Values = True, Allow Multiple Values = False u2013 B1 result. A box that I could enter anything. Defeating the object as I wanted a list of valid options
    3.     A static parameter with a list. Allow custom Values = True, Allow Multiple Values = True u2013 B1 result. A box that I could select multiple values from a list. I could not add my own value. Defeating the object as the list is static
    4.     A static parameter with a list. Allow custom Values = True, Allow Multiple Values = False u2013 B1 result. A drop down box where I could select one of the values. Defeating the object as the list is static
    5.     A static parameter with a list. Allow custom Values = False, Allow Multiple Values = False u2013 B1 result. Same as in point 4
    6.     A Dynamic parameter. Allow custom Values = True, Allow Multiple Values = False u2013 B1 result. Same as in point 1 & 2. No Dynamic list returned and can not add own option
    As mentioned. All the parameters work in Crystal as one expect it to. What I am after is what should I change in B1 so that the report works the same as in Crystal.
    Where in B1 should it be changes and to what should it be changed.
    If the changes should be done in crystal to cater for B1 then what should be changes where to what
    I am not that familiar with B1.
    In my test report I use B1 table OITM.
    My parameter is Item (Crystal syntax {?Item}) and I use it in a filter to say {OITM.ItemCode} = {?Item}
    Regards
    Burger

  • How do I know if my application is running from within WebLogic server

    I have an application that could be running either as a standalone
    application (with its own VM) or as a servlet (within the WebLogic's
    VM). How can the application determine the environment in which it is
    running?

    We have a similar situation here and we took the approach suggested below.
    It does work, however it is creating one problem for us.
    Sometime after the code below executes, our application attempts to
    construct
    the initial JNDI context (in order to look up an EJB Home). In the case
    where
    our application is running outside of a WLS instance, we get the following
    exception:
    Exception in thread "main" java.lang.NoClassDefFoundError:
    weblogic/rjvm/LocalRJ
    VM
    at
    weblogic.t3.services.OutputFilePropertyClient.getValue(OutputFileProp
    ertyClient.java:48)
    at weblogic.rjvm.RJVMManager.initialize(RJVMManager.java:78)
    at weblogic.kernel.Kernel.ensureInitialized(Kernel.java:137)
    at weblogic.rjvm.ServerURL.findOrCreateRJVM(ServerURL.java:182)
    at
    weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLIni
    tialContextFactoryDelegate.java:195)
    at
    weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLIni
    tialContextFactoryDelegate.java:148)
    at
    weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialCont
    extFactory.java:123)
    at
    javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:6
    71)
    at
    javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:242
    at javax.naming.InitialContext.init(InitialContext.java:218)
    at javax.naming.InitialContext.<init>(InitialContext.java:194)
    ... application code here ...
    It would appear that the failed call to getT3Services() is leaving the
    Weblogic client
    runtime in a bad state (if we remove this call, there is no problem
    constructing the
    context).
    So, the question I have is "is there any *safe* way to determine if an
    application is
    running within a WLS?". Thanks in advance for any additional suggestions.
    Sean
    "Wei Guan" <[email protected]> wrote in message
    news:[email protected]...
    Try this:
    boolean isInsideWLAS=false;
    try
    T3Services.getT3Services();
    isInsideWLAS=true;
    catch (Exception e)
    My 2 cents.
    Cheers - Wei
    Cheers - Wei
    Adane Zygta <[email protected]> wrote in message
    news:[email protected]...
    I have an application that could be running either as a standalone
    application (with its own VM) or as a servlet (within the WebLogic's
    VM). How can the application determine the environment in which it is
    running?

  • Tell which Script (or Action) you are running from within that script

    Is there a way within a script to tell the name of the javascript file you are running?
    For example, if I'm running "My Actions/clipOut.jsx" can I set a variable to return "My Actions/clipOut.jsx"?
    (or if I'm running action "Clip Out" of Action Set "My Actions", is there a way to return that info in a script?)
    thanks!!

    dgoldberg
    I'm sorry I wasn't clear in my question:
    As I work on a javascript file I keep my test version on my local machine and push out a final version to a server when my updates are complete.  Then other people access the version on the server to run their actions.  The problem is that I'd like my action to behave differently depending on whether it's the test version or the server version.  If I could get the name/path of the script I'm running (while running the script), I could build out different behaviors whether the version of the script was local or on the server.
    For example, my actions work in unison with many other actions.  It would be nice if my local actions only access other local actions, and server actions only accessed other server actions.
    Does that make sense?

  • Jdbc connection blocks when run from jar

    The following code establishes a connection EXCEPT when run from within a jar file:
    String jdbcDriverName = "oracle.jdbc.driver.OracleDriver";
    String dbConnectionURL = "jdbc:oracle:thin:@192.168.2.7:1521:PRISM";
    String userName = "mdo";
    String password = "mdpass";
    // Load the JDBC driver and create a connection to the database
    Class.forName( jdbcDriverName );
    OracleDataSource dataSource = new OracleDataSource();
    dataSource.setURL( dbConnectionURL );
    dataSource.setUser( userName );
    dataSource.setPassword( password );
    connection = dataSource.getConnection();
    When run from a jar file, the application does not execute beyond the line:
    connection = dataSource.getConnection();
    No exceptions are thrown, it just appears that getConnection never returns.
    Do I need to do anything different to execute this code from within a jar file?
    Thanks in advance,
    Phil
    <><

    When building the JAR file, I inadvertently included files from two Oracle JDBC driver versions (1.2 and 1.4). I was building a single jar file with all files in it.
    I am guessing same named files existed in both driver JARs and caused "confussion" when combined into the single JAR.
    Still, I would have expected an exception to be thrown or a null connection to be returned instead if the thread just blocking.
    Thanks for all replies,
    Phil
    <><

  • Determining the name of the jar file running from JAVA

    Hi everyone,
    This is probably a silly question, but how do you determine the name of the jar file running from within the jar file.
    E.g. If I'm running the jar file "Test.jar", then how can I get the String value "Test.jar" from within my program?
    Any help would be appreciated! Thanks:)

    I think that you can use the solution above to get the jar file resources associated with a particular jar file, and then use the JarFile class to get a manifest of whats in there, and then find your class?
    This is only off of the top of my head, and I haven't tested it. Let me know if it works

  • Jar file - trying to load audio from within it

    I am writing a Game using NetBeans. All works fine when run from within NetBeans, but problems occur when run from a JAR executable.
    The Audio files are not loading. I had a Similar problem with the Images, but resolved it with getResources() etc.
    Any help would be much appreciated, and will post my game when its finished, horray
         * Loads a sequence from the file system. Returns null if
         * an error occurs.
        public Sequence getSequence(String filename)
            try
                return getSequence( new FileInputStream(filename));
            catch (IOException ex)
                ex.printStackTrace();
                return null;
         * Loads a sequence from an input stream. Returns null if
         * an error occurs.
        public Sequence getSequence(InputStream is)
            try
                if (!is.markSupported())
                    is = new BufferedInputStream(is);
                Sequence s = MidiSystem.getSequence(is);
                is.close();
                return s;
            catch (InvalidMidiDataException ex)
                ex.printStackTrace();
                return null;
            catch (IOException ex)
                ex.printStackTrace();
                return null;
        }

    new FileInputStream(filename))That only works for files. Resources in JARs are not files. You should always (when possible) use getClass().getResourceAsStream() to open streams on resources, loading them from the classpath -- regardless of whether your app is a bunch of loose files or in a JAR.

  • Class not being created when running from jar

    Hi all,
    Tech info first:
    IDE: Sun Java Studio Enterprise 8
    Plaform: windows xp
    I have created a Swing app, that connects to a com port(using the RXTXcomm). now, when I run the app in the IDE, everything is fine and dandy, but, when I run the jar file, the application loads, but the class in the app which deals with the com port is not created. here is the code:
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            Main receiver = new Main();
            receiver.getPropertiesFromFile();
            //Create and set up the window.
            frame = new JFrame("R�FILOG RFID Empf�nger");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(receiver.mainPanel);
            frame.setJMenuBar(receiver.createMenuBar());
            frame.addWindowListener(receiver);
            frame.setLocationByPlatform(true);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
            portListener = new RFIDReaderComm(receiver, "COM3");
            portListener.getConfiguration();        
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();   
    portListener in the createAndShowGUI() function is an interface level parameter and is the class that is not being created. There is no error message.
    If I move the two lines that deal with the port listener before the frame.pack() line, then the GUI is not even loaded, and when I view the processes in the task manager, the process starts and then quits without anything becoming visible. So from this I guess there is a problem with creating the class when running from a jar, but without any error messages, I have not a clue where to start...can anyone help?
    thanks in advance.

    Well, some more info, so maybe someone can come up with some tips for me...this is really important, and any help is greatly appreciated.
    This is obviously a classpath problem. After running the my jar file with java -jar I finally got the error NoClassDefFoundError
    Kind of obvious I suppose. But, I cannot seem to get the two jar files I need into the classpath. I have tried the following:
    Updating my computers CLASSPATH with the relevant paths - not working
    Trying to get the Sun Java Studio Enterprise to build the required jar files into the final package - cannot get this to work
    Tried updating the manifest.mf in the following way:
    Created a text file Manifest.txt with the lines:
    Class-Path: RXTXcomm.jar
    Class-Path: BrowserLauncher2-10rc4.jar
    ran the command (in the same directory as Manifest.txt):
    jar cfm RUFILOGScanner.jar Manifest.txt classes/*.class
    but this does not work either. When I run: jar tf RUFILOGScanner.jar all I get is:
    META-INF/
    META-INF/MANIFEST.MF
    classes/
    classes/CRCCalculator.class
    classes/Main$1.class
    classes/Main.class
    classes/RFIDReaderComm.class
    classes/URLDialog$1.class
    classes/URLDialog$2.class
    classes/URLDialog.class
    the classes I want added are not there. Plus, (I think this is because I am running SE8) the manifest.mf is not in a folder called META-INF. In fact, I have no folder called META-INF. Is this significant?
    Please, can anyone help me?

  • Classpath issues when executing from a jar

    I have a jar that I built for an RMI server that has a need to access another jar. (log4j). I run the jar from the command line using:
    java -jar -Djava.rmi.server.codebase=my.jar my.jar
    and the code runs fine but when I try to add in the log4j.jar I can't find it. I have placed it in my.jar in a lib directory within my.jar, I have placed it in the current directory, I have placed it in other directories I know are on the classpath, I have done all kinds of variations with the -classpath switch on the command line and nothing works.
    How do I package, configure and/or call such that the Logger class in log4j.jar can be found by my RMI server when I execute my.jar?
    Thanks

    Running from the jar-file ignores the CLASSPATH. See Bug #4459663
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4459663
    You have a few options:
    First, you can unjar all of the jars you depend on and rejar 'em up with your jar. This is the simplest solution.
    Second, you can skip running "from the jar" and just put that jar in your CLASSPATH.
    Third, you can put jars you depend on in the $JAVA_HOME/jre/lib/ext directory.
    Fourth, you can modify the manifest to specify a classpath, and then put the libraries you depend on at the places specified.
    And, if you think There Ought To Be A Better Way, vote for the RFE!

  • Static method to read text file within JAR.

    I've a small problem. I've got my JAR file stuff working great, so I thought I'd give a go to running it via WebStart. Through a little research, I've found that if you're distributing your application via WebStart, you need to pack up everything in a JAR file. This is no problem for the JDBC drivers, because its already in a JAR, so I should be able to distribute that fine.
    I've managed to digitally sign my application JAR and have a preliminary (i.e. untested) JNLP file set up.
    My problem is, my application gets its available data sources from an external text file. I've already written my own file I/O class which I use in my "commonfiles" package to read in a text file and return it as an array with each element holding a line from the text file. This class is basically just a bunch of static methods.
    So instead of rewriting this, I thought I'd just add a boolean flag to this method to state whether to load this file from the external file system or the JAR file. I've found out that to load a text file from within the JAR you have to use something like: -
    String str = (this.getClass().getResource("/myData.txt")).getFile();
    java.io.File fil = new java.io.File(str);
    java.io.FileReader fr = new java.io.FileReader (fil);
    java.io.BufferedReader bin = new java.io.BufferedReader (fr) ;The sticking point is that my method (ReturnFileAsArray()) is declared as static, because my own FileIO class is just a bunch of static methods to do file I/O stuff. Therefore, I can't use the above method because of the instance variable "this" (I assume).
    Is there any way I can load an included text file as above without having to declare my method as an instance method? I guess I could write a seperate class to do this for my commonfiles package, but I'd rather not if possible.
    Any ideas?

    Don't put a "flag" and code different ways to read files depending on whether it's in a JAR or not. Just use
    the getResource/getResourceAsStream API regardless. Hmmm.....so that will load it from either place depending on the situation? I keep getting a NullPointerException doing that, on this line: -
    String strFileName = (FileIO.class.getResource(fileName)).getFile();...although I've only tried it using the external local filesystem file (in the same directory) as I've not really finished setting up my WebStart stuff yet.
    Here is the method in question...
    public static String[] ReadFileAsArray(String dirName, String fileName, boolean bFromJAR) {
            String[] resultStringArray = null;
            StringBuffer strBuffer = null;
            StringTokenizer strTokenizer = null;
            FileReader fReader = null;
            BufferedReader bReader = null;
            int iElementCount = 0;
            if ((dirName.length() < 1) || (fileName.length() < 1)) {
                // Null parameters found. Failure.
                return null;
            } else {
                // Parameters correct, continue.
                try {
                    // Read the file contents and convert to String array.
                    //if (bFromJAR) {
                        // Open file from within JAR file.
                        String strFileName = (FileIO.class.getResource(fileName)).getFile();
                        File jarFile = new File(strFileName);
                        fReader = new FileReader(jarFile);
                    //} else {
                        // Open from local filesystem.
                    //    fReader = new FileReader(dirName + File.separator + fileName);
                    bReader = new BufferedReader(fReader);
                    strBuffer = new StringBuffer();
                    while (bReader.ready()) {
                        strBuffer.append(bReader.readLine() + "%%");
                    strTokenizer = new StringTokenizer(strBuffer.toString(), "%%");
                    resultStringArray = new String[strTokenizer.countTokens()];
                    while ((strTokenizer.hasMoreTokens()) && (iElementCount < resultStringArray.length)) {
                        resultStringArray[iElementCount++] = strTokenizer.nextToken();
                    bReader.close();
                    return resultStringArray;
                } catch (IOException e) {
                    return null;
        }I'm calling it using: -
    // Load the external file into a String array, one row for each element.
    String[] fileArray = FileIO.ReadFileAsArray(System.getProperty("user.dir"), "datasources.dat", true);Cheers on any info on this.

  • Subreport not displayed when Run from SAP Business One

    We have a crystal report that displays a subreport when it is run from within the Crystal 2008 Designer but not when run from within SAP. Has anybody else seen this error? We have tried importing it into SAP and checking the connections of the report and subreport etc but to no avail.

    Sastry,
    The main report is a document layout with the sub report linked into it using the DocEntry key field from SAP. The subreport should display data based on that link.
    This main report only has the one sub report and when you preview in Crystal it returns data, when you preview using the same criteria but inside of SAP, it is not displayed.
    Thanks
    Mark

  • Loading the SCCM 2012 R2 Cmdlets from within a module

    Hi together,
    In the following article was described how to load the Powershell Module for SCCM 2012:
    http://blogs.technet.com/b/configmgrteam/archive/2013/03/27/powershell-connecting-to-configuration-manager.aspx
    I've taken the code to build a function to load the Powershell Module which works fine when i directly integrate it in my scripts.
    Currently i build a Module called SCCM-HelperFunctions.psm1 and the above mentioned function is one which i want to integrate, i named it "Import-Cmdlets". The Import of my Module works fine,  the function "Import-Cmdlets" is available
    trough IntelliSense and the command ends with no errors in the context of the given Site (ex. "PS CM1:\") but when i try to use SCCM Cmdlets the Command is not found.
    I've checked if the Module was loaded successfully but it isn't. Following is the function included in the Module:
    Function Import-SCCMCmdlets {
    <#
    .SYNOPSIS
    Lädt die SCCM Cmdlets und wechselt in den Kontext der angegebenen Site.
    .DESCRIPTION
    Die Funktion Import-SCCMCmdlets lädt die Powershell Cmdlets und wechselt in den PSDrive Kontext des angegebenen Sitecodes.
    In diesem Kontext können dann die in folgeendem Artikel aufgeführten Cmdlets ausgeführt werden:
    http://technet.microsoft.com/en-us/library/jj821831%28v=sc.20%29.aspx
    .PARAMETER Sitecode
    Eine Zeichenkette mit dem Sitecode der CAS oder Primary Site in dessen Kontext die Cmdlets laufen sollen.
    .EXAMPLE
    Import-SCCMCmdlets -SiteCode "P01"
    .EXAMPLE
    $SiteCode = "P01"
    Import-SCCMCmdlets -SiteCode $SiteCode
    #>
    Param (
    [Parameter(Mandatory=$true)]
    $SiteCode
    $null = Import-Module ($env:SMS_ADMIN_UI_PATH.Substring(0,$env:SMS_ADMIN_UI_PATH.Length – 5) + '\ConfigurationManager.psd1')
    Set-Location "$($SiteCode):" | Out-Null
    if (-not (Get-PSDrive -Name $SiteCode))
    Throw "Beim Versuch das Powershell Modul zu laden und auf das PSDrive $Sitecode zu wechseln trat ein Fehler auf."
    The exact same function works when i copy it to the ISE and run it.
    Does anyone have any ideas and can point me into the right direction? (eventually different workspaces when the function runs from within the module or something like that?)
    Best regards
    Rolf

    Hi together,
    In the following article was described how to load the Powershell Module for SCCM 2012:
    http://blogs.technet.com/b/configmgrteam/archive/2013/03/27/powershell-connecting-to-configuration-manager.aspx
    I've taken the code to build a function to load the Powershell Module which works fine when i directly integrate it in my scripts.
    Currently i build a Module called SCCM-HelperFunctions.psm1 and the above mentioned function is one which i want to integrate, i named it "Import-Cmdlets". The Import of my Module works fine,  the function "Import-Cmdlets" is available
    trough IntelliSense and the command ends with no errors in the context of the given Site (ex. "PS CM1:\") but when i try to use SCCM Cmdlets the Command is not found.
    I've checked if the Module was loaded successfully but it isn't. Following is the function included in the Module:
    Function Import-SCCMCmdlets {
    <#
    .SYNOPSIS
    Lädt die SCCM Cmdlets und wechselt in den Kontext der angegebenen Site.
    .DESCRIPTION
    Die Funktion Import-SCCMCmdlets lädt die Powershell Cmdlets und wechselt in den PSDrive Kontext des angegebenen Sitecodes.
    In diesem Kontext können dann die in folgeendem Artikel aufgeführten Cmdlets ausgeführt werden:
    http://technet.microsoft.com/en-us/library/jj821831%28v=sc.20%29.aspx
    .PARAMETER Sitecode
    Eine Zeichenkette mit dem Sitecode der CAS oder Primary Site in dessen Kontext die Cmdlets laufen sollen.
    .EXAMPLE
    Import-SCCMCmdlets -SiteCode "P01"
    .EXAMPLE
    $SiteCode = "P01"
    Import-SCCMCmdlets -SiteCode $SiteCode
    #>
    Param (
    [Parameter(Mandatory=$true)]
    $SiteCode
    $null = Import-Module ($env:SMS_ADMIN_UI_PATH.Substring(0,$env:SMS_ADMIN_UI_PATH.Length – 5) + '\ConfigurationManager.psd1')
    Set-Location "$($SiteCode):" | Out-Null
    if (-not (Get-PSDrive -Name $SiteCode))
    Throw "Beim Versuch das Powershell Modul zu laden und auf das PSDrive $Sitecode zu wechseln trat ein Fehler auf."
    The exact same function works when i copy it to the ISE and run it.
    Does anyone have any ideas and can point me into the right direction? (eventually different workspaces when the function runs from within the module or something like that?)
    Best regards
    Rolf

  • Executing a Java Program from within a Java Program

    I need to execute the following Java Program from withing another Java Program. The office toolbar command line is
    D:\WINDOWS\system32\java.exe -cp E:\Development\Eclipse\UpdateServer\Classes -server -showversion UpdateServer
    I can find no combination of ProcessBuilder commands, including those that include "Cmd.exe /c" that will make this program run from within another Java Program. All the examples I can find only show how to run Windows *.exe programs. I keep getting error 123 from ProcessBuilder.start(), but I can find no documentation for error 123.

    Assuming your code didn't get mangled by the forum
    (it's missing one "), it may be that your "-cp
    E:\\Develop.." argument is getting quoted as it has a
    space in it; try passing "-cp" and "E:\\Develop..."
    as two arguments.That worked; specifically the following tested OK:
    ProcessBuilder pb = new ProcessBuilder("D:\\WINDOWS\\System32\\Java.exe", "-cp", "E:\\Development\\Eclipse\\UpdateServer\\Classes\\", "-server", "-showversion", "UpdateServer" );
    pb.directory(new File("E:\\Development\\Eclipse\\UpdateServer\\Classes\\"));
    try{
         Process p = pb.start();
         InputStream is = p.getErrorStream();
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader br = new BufferedReader(isr);
         String line;
         while ((line = br.readLine()) != null)
              System.out.println(line);
         p.waitFor();
    }catch(IOException ioe){
    I was sure I tried that exact same code before, and it did not work, but now it does, at least at the top level (when it is in main of a test program). I will have to wait to try it until later when it is buried deep in a subroutine.

Maybe you are looking for