Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Java Compiler

  1. #1
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Java Compiler

    Hi everyone!
    I'm creating a program that will compile and run another java program:
    Lets say I have a program in directory
    D:\HelloWorld\src
    and compiled program will be in
    D:\HelloWorld\bin
    inside src and bin is a folder hello (that's a package)
    package hello;
     
    public class HelloWorld {
     
    	public static void main(String[] args) {
    		System.out.println("Hello World");
    		System.out.println("Hello World");
    	}
    }

    This program will be run by another program (that's the program that I am creating)
    Here is the code of my program:
    package runnercompiler;
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    public final class RunnerCompiler {
     
        public static void main(String[] args) throws IOException, InterruptedException {
            RunnerCompiler compiler = new RunnerCompiler();
            String command = "javac -d D:\\HelloWorld\\bin D:\\HelloWorld\\src\\hello\\HelloWorld.java";
            ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", command);
            Process process = processBuilder.start();
            OutStreamAccumulator out = compiler.new OutStreamAccumulator(process.getInputStream());
            out.start();
            /* to make sure that the other thread will finish compile the HelloWorld first before doing next statement */
            out.join();
            command = "java -classpath D:\\HelloWorld\\bin hello.HelloWorld"; // running the HelloWorld
            processBuilder = new ProcessBuilder("cmd", "/c", command);
            process = processBuilder.start();
            out = compiler.new OutStreamAccumulator(process.getInputStream());
            out.start();
            out.join();
        }
     
        private class OutStreamAccumulator extends Thread {
     
            private InputStream inStream;
     
            public OutStreamAccumulator(InputStream inStream) {
                this.inStream = inStream;
            }
     
            @Override
            public void run() {
                try {
                    int value;
                    while ((value = inStream.read()) != -1) {
                        System.out.print((char) value);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(RunnerCompiler.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    That works fine.
    and it will print:
    Hello World
    Hello World

    Problem
    The problem is, how can I get the error messages that will occur
    if the program crashes because of exception?
    or the program falls into catch and the catch block prints
    the error using stackTrace or Logger?
    Below code is example of my problem:

    Lets say I edited my HelloWorld program:
    package hello;
     
    public class HelloWorld {
     
    	public static void main(String[] args) {
    		System.out.println("Hello World");
    		System.out.println("Hello World");
    		try {
    			Integer.parseInt("a"); // line 9
    		} catch (NumberFormatException ex) {
    			ex.printStackTrace();
    			System.out.println("Error");
    		}
    		System.out.println("Done");
    	}
    }
    Obviously, it caught an exception at line 9
    when my RunnerCompiler program runs, it prints
    Hello World
    Hello World
    Error
    Done

    Well, it didn't printed out the exception error.
    I hope someone knows how to get that exception message..
    Thanks a lot


  2. #2
    Member
    Join Date
    Feb 2014
    Location
    India
    Posts
    47
    My Mood
    Bored
    Thanks
    0
    Thanked 7 Times in 7 Posts

    Default Re: Java Compiler

    It prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err.

    --- Update ---

    You may use either of the following

    ex.printStackTrace(PrintStream s)
     
    Prints this throwable and its backtrace to the specified print stream.
     
    Parameters:
        s - PrintStream to use for output

    or

    ex.printStackTrace(PrintWriter s)
     
    Prints this throwable and its backtrace to the specified print writer.
     
    Parameters:
        s - PrintWriter to use for output


    --- Update ---

    System.setErr(System.out);

    This is not recommended though but this will solve your problem.

  3. #3
    Junior Member
    Join Date
    Feb 2014
    Posts
    7
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Java Compiler

    OutStreamAccumulator out = compiler.new OutStreamAccumulator(process.getInputStream());
    getInputStream returns the only input stream connected to the normal output of the subprocess.
    try using getErrorStream to print the errors associated with the subprocess.
    you can refer this Process (Java Platform SE 7 )

  4. The Following User Says Thank You to RESHAM For This Useful Post:

    dicdic (February 20th, 2014)

  5. #4
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Re: Java Compiler

    getInputStream returns the only input stream connected to the normal output of the subprocess.
    try using getErrorStream to print the errors associated with the subprocess.
    your right, it works now.
    but there's a little problem
    I edited my RunnerCompiler code, this the new one:
    package runnercompiler;
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    /**
     *
     * @author PS.BMFuentes
     */
    public final class RunnerCompiler {
     
        public static void main(String[] args) throws IOException, InterruptedException {
            RunnerCompiler compiler = new RunnerCompiler();
            String command = "javac -d D:\\HelloWorld\\bin D:\\HelloWorld\\src\\hello\\HelloWorld.java";
            ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", command);
            Process process = processBuilder.start();
            OutStreamAccumulator out = compiler.new OutStreamAccumulator(process.getInputStream(), process.getErrorStream());
            out.start();
            out.join();
            command = "java -classpath D:\\HelloWorld\\bin hello.HelloWorld";
            processBuilder = new ProcessBuilder("cmd", "/c", command);
            process = processBuilder.start();
            out = compiler.new OutStreamAccumulator(process.getInputStream(), process.getErrorStream());
            out.start();
            out.join();
        }
     
        private class OutStreamAccumulator extends Thread {
     
            private InputStream inStream, errorStream;
     
            public OutStreamAccumulator(InputStream inStream, InputStream errorStream) {
                this.inStream = inStream;
                this.errorStream = errorStream;
            }
     
            @Override
            public void run() {
                try {
                    int value, error = 0;
                    while ((value = inStream.read()) != -1 || (error = errorStream.read()) != -1) {
                        if (value > 0) {
                            System.out.print((char) value);
                        }
                        if (error > 0) {
                            System.out.print((char) error);
                        }
                    }
                } catch (IOException ex) {
                    Logger.getLogger(RunnerCompiler.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    its out put is:
    Hello World
    Hello World
    Error
    Done
    Feb 21, 2014 9:14:57 AM hello.HelloWorld main
    SEVERE: null
    java.lang.NumberFormatException: For input string: "a"
    at java.lang.NumberFormatException.forInputString(Unk nown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at hello.HelloWorld.main(HelloWorld.java:9)

    with this message, as programmer, I can say that the error was located at
    line 12 of my HelloWorld program because of the last line of the output.
    And I can trace it easily because there is a line number on left side of notepad++.

    The little problem is,
    the error message printed after printing the normal message.
    the error message should have printed before the printing Error or after printing
    the second Hello World.
    Well, I don't know if that's possible.
    but it would be better if it's possible, thanks for the help.

    ----------------------------------------------------------------------------------------------------

    It prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err.
    did you mean to use ex.printStackTrace(PrintWriter s) in HelloWorld program?
    I think that is not an option for me.
    I think there is no reason to use PrintWriter or PrintStream class just to print Hello World program.
    (or the real programs that I'm going to create).
    I don't want to use those classes just to execute RunnerCompiler class perfectly.

    The reason I'm creating this is to easily compile and run java programs
    in our server.
    Something like getting all java, jar files, and compile it, and then getting all the classes, jar files and run it,
    as long as it is java, classes, and jar files are properly separated like what an IDE does.

    Thanks for the help RESHAM and ankurt!

  6. #5
    Member
    Join Date
    Feb 2014
    Location
    India
    Posts
    47
    My Mood
    Bored
    Thanks
    0
    Thanked 7 Times in 7 Posts

    Default Re: Java Compiler

    ex.printStackTrace(PrintWriter s) is not to print the Hello World. It is used to change the stream of stackTrace being printed.

    using
    System.setErr(System.out);
    you can route all your error messages to the standard output stream.

    Although your problem has been solved by RESHAM's reply, but still you may check this one if this solves your order of printing problem.

  7. #6
    Junior Member
    Join Date
    Feb 2014
    Posts
    7
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Java Compiler

    while ((value = inStream.read()) != -1 || (error = errorStream.read()) != -1) {
                        if (value > 0) {
                            System.out.print((char) value);
                        }
                        if (error > 0) {
                            System.out.print((char) error);
                        }
                    }
    so after printing the second "hello World" , the 1st condition of while loop stilll remains true as "Error" is read as normal ouput. so the 2nd condition of while loop is not checked. and "Error" is printed. now in the next iteration the 1st condition of while loop becomes false so it checks for the error stream and prints it.

  8. #7
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Re: Java Compiler

    so after printing the second "hello World" , the 1st condition of while loop stilll remains true as error is read as normal ouput. so the 2nd condition of while loop is not checked. and error is printed. now in the next iteration the 1st condition of while loop becomes false so it checks for the error stream and prints it.
    I think that's not the problem.
    if we try this code:
                    do {
                        value = inStream.read();
                        error = errorStream.read();
                        if (value > 0) {
                            System.out.print((char) value);
                        }
                        if (error > 0) {
                            System.out.print((char) error);
                        }
                    } while(value > -1 || error > -1);
    it will print:
    Hjealvlao. lWaonrgl.dN
    u
    mHbeelrlFoo rWmoartlEdx
    c
    eEprtrioorn
    :
    DFoonre
    i
    nput string: "a"
    at java.lang.NumberFormatException.forInputString(Unk nown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at hello.HelloWorld.main(HelloWorld.java:12)

    as you noticed it print each character one after another,
    if we analyzed it, it seems that there's no way (I'm not sure)
    to figure out at where part of the output prints an error.
    the problem here, I think is determining where an Exception occurs.
    that's the reason why I doubt if it's possible to do.

    the 1st condition of while loop stilll remains true as error is read as normal ouput. so the 2nd condition of while loop is not checked.
    yeah, you are right about that.
    -----------------------------------------------------------------------------------------------------------------------------------------------

    ex.printStackTrace(PrintWriter s) is not to print the Hello World. It is used to change the stream of stackTrace being printed.
    what I mean is I don't want PrintWriter class to use when Exception caught at HelloWorld program.
    I think printStackTrace() (no parameter) method will do better.



    Thanks RESHAM and ankurt.
    I think it's okay, as long as I get what the error message is all about.

  9. #8
    Junior Member
    Join Date
    Feb 2014
    Posts
    7
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Java Compiler

    value = inStream.read();
    error = errorStream.read();
    read() reads next byte of data from input stream
    so in the 1st iteration its (char)value=h and (char)error=j. you are reading one character from input stream and one character from eroor stream and printing it simultaneously.

Similar Threads

  1. Simple Java compiler
    By cazanova in forum Java Theory & Questions
    Replies: 2
    Last Post: May 29th, 2013, 02:09 AM
  2. develop compiler in java
    By olfat in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 22nd, 2013, 08:48 AM
  3. Creating a Compiler in Java
    By Superstar288 in forum Java Theory & Questions
    Replies: 20
    Last Post: February 22nd, 2013, 08:05 AM
  4. Java Online Compiler
    By sb24 in forum Java Theory & Questions
    Replies: 15
    Last Post: March 23rd, 2012, 09:50 AM
  5. Java 6.0 Compiler Error
    By jilomes in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 19th, 2011, 04:34 PM