How to capture output of java files using Runtime.exec

Hi guys,
I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
import java.io.*;
public class CmdExec {
  public CmdExec() {
  public static void main(String argv[]){
     try {
     String line;
     Runtime rt = Runtime.getRuntime();
     String[] cmd = new String[2];
     cmd[0] = "javac";
     cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
     Process proc = rt.exec(cmd);
     cmd = new String[2];
     cmd[0] = "javac";
     cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
     proc = rt.exec(cmd);
     //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
     BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
     while ((line = input.readLine()) != null) {
        System.out.println(line);
     input.close();
    catch (Exception err) {
     err.printStackTrace();
public class E {
    public static void main(String[] args) {
        System.out.println("hello world!!!!");
}Please help :)

Javapedia: Classpath
How Classes are Found
Setting the class path (Windows)
Setting the class path (Solaris/Linux)
Understanding the Java ClassLoader
java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

Similar Messages

  • Can we run a java application using Runtime.exec()?

    Can we run a java application using Runtime.exec()?
    If yes what should i use "java" or "javaw", and which way?
    r.exec("java","xyz.class");

    The best way to run the java application would be to dynamiically load it within the same JVM. Look thru the class "ClassLoader" and the "Class", "Method" etc...clases.
    The problem with exec is that it starts another JVM and moreover you dont have the interface where you can throw the Output directly.(indirectly it can be done by openong InputStreams bala blah............). I found this convenient. I am attaching part of my code for easy refernce.
    HIH
    ClassLoader cl = null;
    Class c = null;
    Class cArr[] ;
    Method md = null;
    Object mArr[];
    cl = ClassLoader.getSystemClassLoader();
    try{
         c = cl.loadClass(progName.substring(0,progName.indexOf(".class")) );
    } catch(ClassNotFoundException e) {
    System.out.println(e);
         cArr = new Class[1] ;
         try{
         cArr[0] = Class.forName("java.lang.Object");
         } catch(ClassNotFoundException e) {
         System.out.println(e);
         mArr = new Object[1];
         try{
         md = c.getMethod("processPkt", cArr);
         } catch(NoSuchMethodException e) {
         System.out.println(e);
         } catch(SecurityException e) {
         System.out.println(e);
    try {            
    processedPkt = md.invoke( null, mArr) ;
    } catch(IllegalAccessException e) {
              System.out.println(e);
    } catch(IllegalArgumentException e) {
              System.out.println(e);
    }catch(InvocationTargetException e) {
              System.out.println(e);
    }catch(NullPointerException e) {
              System.out.println(e);
    }catch(ExceptionInInitializerError e) {
              System.out.println(e);
    }

  • Spawn a java process using runtime.exec() method

    Hi,
    This is my first post in this forum. I have a small problem. I am trying to spawn a java process using Runtime.getRuntime().exec() method in Solaris. However, there is no result in this check the follwoing program.
    /* Program Starts here */
    import java.io.*;
    public class Test {
    public static void main(String args[]) {
    String cmd[] = {"java", "-version"};
    Runtime runtime = Runtime.getRuntime();
    try{
    Process proc = runtime.exec(cmd);
    }catch(Exception ioException){
    ioException.printStackTrace();
    /* Program ends here */
    There is neither any exception nor any result.
    The result I am expecting is it should print the following:
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
    Please help me out in this regard
    Thanks in advance
    Chotu.

    Yes your right. It is proc.getInputStream() or proc.getErrorStream(). That is what I get for trying to use my memory instead of looking it up. Though hopefully the OP would have seen the return type of the other methods and figured it out.

  • Problem wiht Running Batch File using Runtime.exec()

    I am writting one program which will create a jar file using a windows Batch file.
    The main program is in the folder "d:\CmdExec.java".
    The other one to which a jar file to be created is in the folder "e:\folder\HelloWorld.class"
    The contents inside the "e:\folder" are
    e:\folder\HelloWorld.class
    e:\folder\mainClass.txt
    e:\folder\run.bat
    The mainClass.txt contains "Main-Class: HelloWorld"
    The Run.bat file contains "jar cmf mainClass.txt HelloWorld.jar *.class"
    The coding for CmdExec.java is as follows
    import java.io.*;
    import java.awt.Desktop;
    public class CmdExec {
    public static void main(String argv[]) {
    try {
    Desktop desktop = null;
    if (Desktop.isDesktopSupported()) {
    desktop = Desktop.getDesktop();
    desktop.open(new File("e:\\folder\\run.bat"));
    catch (Exception err) {
    err.printStackTrace();
    When i double click the file e:\folder\Run.bat, it will create a jar file for HelloWorld.class.
    But, i want to create that jar file using the java program CmdExec.java.
    When i run CmdExec.java, the batch file is opened. But it shows error as "Can't find the specified file"
    But when i copy the following files to "d:\",
    e:\folder\HelloWorld.class
    e:\folder\mainClass.txt
    the jar file is created using the CmdExec.java.
    But,
    e:\folder\HelloWorld.class
    e:\folder\mainClass.txt
    these files should be in the folder"e:\folder" only.
    Can anyone Help me this Problem?
    Or Anyother way for creating a jar file for one program by using another program?
    Help me soon.............

    Try this. It's not running a bat file. You can say it almost is a bat file.
    import java.io.*;
    import java.util.Scanner;
    public class CmdExec {
        public static void main(String argv[]) {
            try {
                Process p = Runtime.getRuntime().exec("jar cmf mainClass.txt HelloWorld.jar *.class");
                Scanner s1=new Scanner(new InputStreamReader(p.getInputStream()));
                while(s1.hasNextLine())
                    System.out.println(s1.nextLine());
                p.waitFor();
                System.out.println(p.exitValue());
                if(p.exitValue()==0)
                    System.out.println("Okay");
                else
                    System.out.println("Error");
            catch (Exception ex) {
                ex.printStackTrace();
    }Run it in the same folder as mainClass.txt
    Edited by: ColacX on Aug 1, 2008 10:35 AM

  • Start a new java process using Runtime.Exec() seems to ignore the -Xmx

    I am working with a process that requires a minimum of 1.5 GB to run and works better if more is available.
    So I am determining how much memory is available at startup and restarting the jre by calling
    Runtime.exec("java -Dcom.sun.management.jmxremote=true -Xmx1500M -jar XXX.jar")
    which reinvokes the same process with a new max memory size.
    The initial call to the process is
    java -Dcom.sun.management.jmxremote=true -Xmx3500M -jar XXX.jar
    The initial call returns 3262251008 from Runtime.maxmemory()
    When reinvoked through Runtime.exec() as above
    Runtime.maxmemory() still returns 3262251008
    Is there a way to separate the new process from the size specified by the parent process?

    That is strange. Here is a program I wrote which calls itself recursively.
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    import java.util.ArrayList;
    import static java.util.Arrays.asList;
    public class MemorySize {
        public static void main(String... args) throws IOException, InterruptedException {
            System.out.println("Maximum memory size= "+Runtime.getRuntime().maxMemory());
            if (args.length == 0) return;
            List<String> cmd = new ArrayList<String>();
            cmd.add("java");
            cmd.add("-cp");
            cmd.add(System.getProperty("java.class.path"));
            cmd.add("-Xmx"+args[0]+'m');
            cmd.add("MemorySize");
            cmd.addAll(asList(args).subList(1,args.length));
            Process p = new ProcessBuilder(cmd).start();
            readin(p.getErrorStream());
            readin(p.getInputStream());
        private static void readin(final InputStream in) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        byte[] bytes = new byte[1024];
                        int len;
                        while((len = in.read(bytes))>0)
                            System.out.write(bytes, 0, len);
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
            }).start();
    }If you run this with the args 128 96 33 222 it prints out
    Maximum memory size= 66650112
    Maximum memory size= 133234688
    Maximum memory size= 99942400
    Maximum memory size= 35389440
    Maximum memory size= 231014400

  • How can i launch another java application using Runtime class?

    I created a java process which invokes another java application called Launch as shown below,
    Process p=Runtime.getRuntime().exec("java -classpath=C:\\Program Files\\bin\\nettools\\ui\\updates Launch");
    But it is not working...can any one help me on this?
    Edited by: deepakchandaran on Sep 20, 2007 7:10 AM

    You could search the forum and Google.
    it has been answered before.
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • How to open an .txt file or .doc file using Runtime.exec()?

    Thanks

    Do:String[] cmdLineArray = new String[3];
    cmdLineArray[0] = "cmd.exe";
    cmdLineArray[1] = "/c";
    cmdLineArray[2] = yourCompletePathFile;
    Runtime.getRuntime().exec(cmdLineArray);

  • Problem in opening a doc file using Runtime.exec()

    Code:
    import java.io.*;
    class StreamGobbler extends Thread {
        InputStream is;
        String type;
        StreamGobbler(InputStream is, String type) {
            this.is = is;
            this.type = type;
        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null) System.out.println(type + ">" + line);   
            catch (IOException ioe) {
                 ioe.printStackTrace(); 
    public class GoodWindowsExec {
        public static void main(String args[]) {
             String file = "test.doc";
             String appPath = "/C";
            try {
                String osName = System.getProperty("os.name" );
                System.out.println("OS : " + osName);
                String[] cmd = new String[3];
                if( osName.equals( "Windows NT" ) || osName.equals( "Windows XP" )) {
                    cmd[0] = "cmd.exe" ;
                    cmd[1] = appPath;
                    cmd[2] = file;
                else if( osName.equals( "Windows 95" ) ) {
                    cmd[0] = "command.com" ;
                    cmd[1] = appPath;
                    cmd[2] = file;
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
                Process proc = rt.exec(cmd);
                // any error message?
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");           
                // any output?
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            catch (Throwable t) {
                t.printStackTrace();
    }I got this code from internet. Program will work fine if my "test.doc" is in "C:\test.doc" directory. Is there any way to get the application path and open the doc file or how to give a specified path for my doc file
    EG:- "C:\TestDir\test.doc"
    Thanks

    Well /C is not the path to the app. It is a switch to
    the command line.
    set your file name to "C:/test.doc"
    ~TimSorry, I guess my reply doesn't really answer the problem. But you can supply the entire path as part of the file name string.
    String file = "C:/Path/To/My/File/to execute/test.doc"

  • Invoking "java myClass" using Runtime.Exec from a Java Stored Procedure

    Hi All,
    This is regarding the use of Runtime.getRunTime().exec, from a java programme (a Java Stored Procedure), to invoke another Java Class in command prompt.
    I have read many threads here where people have been successuful in invoking OS calls, like any .exe file or batch file etc, from withing Java using the Runtime object.
    Even i have tried a sample java programme from where i can invoke notepad.exe.
    But i want to invoke another command prompt and run a java class, basically in this format:
    {"cmd.exe","java myClass"}.
    When i run my java programme (in command prompt), it doesnt invoke another command prompt...it just stays hanging.
    When i run the java programme from my IDE, VisualCafe, it does open up a command prompt, but doesnt get the second command "java myCLass".
    Infact on the title of the command prompt (the blue frame), shows the path of the java.exe of the Visual Cafe.
    and anyway, it doesnt run my java class, that i have specified inside the programme.
    Even if i try to run a JAR file, it still doesnt do anything.
    (the JAR file other wise runs fine when i manually invoke it from the command prompt).
    Well, my question is, actually i want to do this from a Java Stored Procedure inside oracle 8.1.7.
    My feeling is, since the Java Stored Procedure wont be running from the command prompt (i will be actually invoking it through a Oracle trigger), it may be able to invoke the command prompt and run the java class i want. and that java class has to run with the SUn's Java, not Oracle JAva.
    Does any one have any idea about it?
    Has anyone ever invoked a java class or JAR file in command prompt from another Java Programme?
    YOur help will be highly appreciated.
    (P:S- Right now, my database is being upgraded, so i havent actually been able to create a Java Stored procedure and test it. But i have tested from a normal java programme running in command prompt and also from Visual Cafe).
    Thanks in advance.
    -- Subhasree.

    Hello Hari,
    Thanks for your quick reply.
    Can you please elaborate a little more on exactly how you did? may be just copy an dpaste taht part of teh code here?
    Thanks a lot in advance.
    --Subhasree                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem of executing a process under Linux using Runtime.exec

    Hi, All
    I am having a problem of executing a process under Linux and looking for help.
    I have a simple C program, which just opens a listening port, accept connection request and receive data. What I did is:
    1. I create a script to start this C program
    2. I write a simple java application using Runtime.exec to execute this script
    I can see this C program is started, and it is doing what it supposed to do, opening a listening port, accepting connection request from client and receiving data from client. But if I stop the Java application, then this C program will die when any incoming data or connection request happens. There is nothing wrong with the C program and the script, because if I manually execute this script, everying works fine.
    I am using jre1.4.2_07 and running under Linux fedora 3.0.
    Then I tried similar thing under Windows XP with service pack2, evrything works OK, the C program doesn't die at all.

    Mind reading is not an exact science but I bet that you are not processing either the process stdout or the stderr stream properly. Have you read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html ?

  • How do I produce an excel file using java code

    How do i produce an excel file using java code.
    If it is possible would ne one have ne source code as an example.
    I have tried looking up information on outputing the information to a *.csv file but unfortunality i have had no luck in finding any information. To be exact ne source code.
    Thanks
    Lee

    That's what I use and I'd be the first to admit that it's very messy. But it works. Go use Google and see what else you can find.

  • How to compile Java files using Ant in Eclipse

    Hi All ,
    I would like to compile all Java files using Ant in Eclipse.Since am very new to Ant and Eclipse can someone help me to create a build.xml file and let me know how to compile all the java files.
    For ex , I have placed my java files inside the path C:\HEC\Terab.Initially the Terab folder holds 7 jar files which i had decompiled using JD compiler and placed the unzipped 7 folders (which contains the java files ).Now i have imported the HEC project into Eclipse using New ->Project ->Java Project.after importig it throwed me an error saying missing jar files.again i copied the jar files and placed inside Terab folder with other 7 folder.
    Now How i can compile the java files and convert in to class files.Then after compiling the files i will again need to jar all the 7 folder.
    Please tell me the steps i need to follow.How to write an build.xml file ? where i should keep it ? only one build.xml file is enough or should i write 7 build.xml file for each folder ? Please help me out...
    Thanks & Regards
    Kar1983

    put it another way, what I am trying to do is to compile David Brackeen's ch 18 code from his book. The java sourse files can be downloaded here:
    http://www.brackeen.com/javagamebook/
    my question is that how would I complie all of these file so that I can get the program in ch18src\src\com\brackeen\javagamebook\test\ to run?

  • 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".

  • How to compile and run java files on a mac using command line?

    can someone tell me or link me to some article on how to compile and run java files from command line on a mac? I have mac OS X leopard

    What do you mean by "where to put them" ? What do you want to put anywhere ?
    Have you read Peter's comment in brackets ? Perhaps you have a classpath problem ?
    Edited by: Michael_Knight on Aug 31, 2008 4:23 AM

  • How to write a CLOB to file using UTF-8

    I'm new to java and I have the following problem.
    I need to write a CLOB to file using the UTF-8 characterset (I'm generating an xml file). My database characterset is WE8ISO8859P15.
    I've tried the code below but the resulting output fails validation in an xml editor due to an 'invalid character' error :
    create or replace
    and compile
    java source named "ClobUtil"
    as
    import java.io.*;
    import java.lang.*;
    import java.sql.*;
    import java.util.*;
    import oracle.jdbc.driver.*;
    import oracle.sql.*;
    public class ClobUtil {
    public static void save(CLOB clob, String filename) throws Exception
    Connection conn = DriverManager.getConnection("jdbc:oracle:kprb:");
    conn.setAutoCommit(false);
    InputStream is = clob.getCharacterStream();
    FileOutputStream os = new FileOutputStream(filename);
    int size = clob.getChunkSize();
    byte buffer[] = new byte[size];
    int length;
    while ((length = is.read(buffer, 0, size)) != -1) {
    os.write(buffer, 0, length);
    is.close();
    os.close();
    conn.close();
    I see that the getCharacterStream() method returns a Unicode character stream but how do I output this to file ??
    Thanks in advance

    File file = new File( "myfile.utf8" );
    FileOutputStream fos = new FileOutputStream( file );
    OutputStreamWriter osw = new
    OutputStreamWriter( fos, "UTF8" );
    Writer w = new BufferedWriter( osw );
    PrintWriter out = new PrintWriter( w );
    Or whatever you need. Note that this merely allows you to specify the encoding to be used in the output file, it does convert the encoding for you. I think in your case this will work since you already know the output stream will not contain the full range of UTF8 characters anyway.

Maybe you are looking for

  • Report for stock value at Warehouselevel

    Hi I need to generate  a report of stock value at the warehouse level. please let me know the tables to be linked to get the report. Thanks

  • Newest itunes not playing correctly

    newest update. I usually play an album at a time, either from a remote (ipod touch) or direct. Now- shuffle will turn itself on and start playing random after the first song or itunes will add tracks (a second album) to the playlist. Previously; I pi

  • Connecting "regular" speakers to MacPro

    Okay, I had a G4 Mirrored door that I used a Griffin ProSpeaker Breakout adapter to connect my Tannoy monitors using regular speaker wire. With its internal amp, this was a great way to take advantage of the G4. Anybody know if the new MacPro has the

  • Order Infinity before exchange live?

    With my exchange being scheduled to go live on 30 June, I've been going to the infinity checker daily to see when I am able to place an order. Today was the first time that it has told me that Infinity is available 'now' on my line and I was able to

  • Display additional fields in Service Request detail page

    Hi All, Is it possible to display some fields like Account Type, Contact Type etc. in Service Request detail page? Service Request Field Edit page only allows to add default value to the newly created field, that's not the result that I needed. Any s