Unix terminal in java

Hi all, I am working on a project which will allow a person to be working on code and have other users sign in and post comments to there code to help them with problems. One of the features I wanted to have is a terminal windows in which the user could compile and run their code and allow other users to view the output. I was going to just have a compile and run button and show the output using runtime.exec(<java or javac>) but I though it would be much more useful to have a full terminal window. So far I am able to run runtime.exec(�tcsh -i�) in a text area and have it process the text typed. The problem, I have is that the command prompt only show up when it executes a command that has output and executes correctly (for example ls). With a simple return or cd it will not output a command prompt until I do something like an ls again, in that case it will output as many prompts as I have hit returns. I would like it to work as closely to as possible to any gome-terminal or like terminal that we all use daily. Any help you be greatly appreciated, thank a lot in advance.
Kyle
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class JavaTerminal extends JPanel {
    TextArea ta;
    InputStream in;
    InputStream err;
    OutputStream out;
    public JavaTerminal() { //throws IOException {
        try {
            String[] envp = null;
            File dir = new File(".");
            Process p = Runtime.getRuntime().exec("tcsh -i", envp, dir);
            in = p.getInputStream();
            err = p.getErrorStream();
            out = p.getOutputStream();
        } catch (IOException e) {
            System.err.println("Cannot create JavaTerminal: " + e);
            e.printStackTrace();
            System.exit(-1);
        ta = new TextArea(24,70);
        setLayout(new BorderLayout());
        add(ta, BorderLayout.CENTER);
        ta.addKeyListener(new KeyListener() {
            PrintWriter  pw = new PrintWriter(new OutputStreamWriter(out));
            public void keyPressed(KeyEvent e) { }
            public void keyReleased(KeyEvent e) {
                char text = e.getKeyChar();
                System.out.println(text);
                pw.print(text);
                pw.flush();
            public void keyTyped(KeyEvent e) { }
        (new Thread(new Runnable() {
            public void run() {
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String line = null;
                int b;
                try {
                    while((line = br.readLine()) != null) {
                        ta.append(line + "\n");
                } catch (IOException e) {
                    ta.append("IOException reading stdout: " + e);
                    e.printStackTrace();
        })).start();
        (new Thread(new Runnable() {
            public void run() {
                BufferedReader br = new BufferedReader(new InputStreamReader(err));
                String line = null;
                try {
                    while((line = br.readLine()) != null) {
                        ta.append(line + "\n");
                } catch (IOException e) {
                    ta.append("IOException reading stderr: " + e);
                    e.printStackTrace();
        })).start();
    public static void main(String[] argv) {
        Frame f = new Frame("Java Terminal");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);}
        JavaTerminal jt = new JavaTerminal();
        f.add(jt, BorderLayout.CENTER);
        f.pack();
        f.setVisible(true);
}

Well I solved the problem I was having. Apparently you can not buffer the input and output streams of a process, and I also believe the input and output must be of the same type of stream, or at least the same encoding, which makes sense. Now just to figure out how to restrict the caret position and how to handle back space and other special keys for a fully functional unix terminal in a JPanel. Thanks to any one who read my post and tried to figure it out. I am posting my corrected code so far for other who would like to try something like this. Any suggestions on how to handle my next few problems would be appreciated as well.
Kyle
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class JavaTerminal extends JPanel {
    TextArea ta;
    InputStream in;
    InputStream err;
    OutputStream out;
    public JavaTerminal() {
        ta = new TextArea(24,70);
        setLayout(new BorderLayout());
        add(ta, BorderLayout.CENTER);
        try {
            String[] envp = null;
            File dir = new File(".");
            Process p = Runtime.getRuntime().exec("tcsh -i", envp, dir);
            in = p.getInputStream();
            err = p.getErrorStream();
            out = p.getOutputStream();
        } catch (IOException e) {
            ta.append("IOException getting streams: " + e);
            e.printStackTrace();
        ta.addKeyListener(new KeyListener() {
            OutputStreamWriter osw = new OutputStreamWriter(out);
            public void keyPressed(KeyEvent ke) { }
            public void keyReleased(KeyEvent ke) {
                char text = ke.getKeyChar();
                try {
                    osw.write(text);
                    osw.flush();
                } catch (IOException e) {
                    ta.append("IOException writeing stdout: " + e);
                    e.printStackTrace();
            public void keyTyped(KeyEvent ke) { }
        (new Thread(new Runnable() {
            public void run() {
                InputStreamReader isr = new InputStreamReader(in);
                int i;
                try {
                    while((i = isr.read()) != -1) {
                        ta.append(String.valueOf((char)i));
                } catch (IOException e) {
                    ta.append("IOException reading stdin: " + e);
                    e.printStackTrace();
        })).start();
        (new Thread(new Runnable() {
            public void run() {
                InputStreamReader isr = new InputStreamReader(err);
                int i;
                try {
                    while((i = isr.read()) != -1) {
                        ta.append(String.valueOf((char)i));
                } catch (IOException e) {
                    ta.append("IOException reading stderr: " + e);
                    e.printStackTrace();
        })).start();
    public static void main(String[] argv) {
        Frame f = new Frame("Java Terminal");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);}
        JavaTerminal jt = new JavaTerminal();
        f.add(jt, BorderLayout.CENTER);
        f.pack();
        f.setVisible(true);
}

Similar Messages

  • Problem on Creating Unix Termial in java like windows command prompt

    hi all,
    i created an unix terminal using java swing(to connect unix server and executing commands). here i redirect the console output to textarea. The problem is i can't read the input from the textarea. and another problem is how to disable the editable option in the textarea before to the command read line. The terminal is like a putty. Any One Please give a suggestion for this problem.

    sabre150 wrote:
    georgemc wrote:
    LinaGsp wrote:
    5)then I run this command "jar cvfm MyJar.jar manifest.mf .class"If this is exactly what you did, and not a typo, that's probably your problem. Do you have a file called .class?It is more likely that the forum markup is getting in the way.Of course it is! D'oh! I seem to have a blind spot to that, I never take it into consideration...
    OP, listen to these guys, ignore this blind old fool :-(

  • Call an interactive UNIX command from java

    Hi,
    I want to call a UNIX command from java. When issue the command 'htpasswd -c filename username' on UNIX terminal, it asks for the new password and the then confirmation password again (yeah, unfortunately the htpasswd installed on our system does not allow you proivde the password on the command line. So have to work interactively ). Now, I have written a simple java program RunCommand.java. I am hardcoding the password for the htpasswd command in the file (in the real situation, password will be generated dynamically). I want to issue 'java RunCommand' on the UNIX command line and get back the command prompt without being asked for the password twice. The code is below, but the Outputstream does not work as expected. It always asks for inputs. Any idea? Many thanks.
    import java.io.*;
    public class RunCommand {
    public static void main(String args[]) throws Exception {
    String s = null;
    try {
    String cmd = "htpasswd -c filename username ";
    // run a Unix command
    Process p = Runtime.getRuntime().exec(cmd);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    OutputStream stdOut = p.getOutputStream();
    String pswd = "mypassword";
    while ((s = stdInput.readLine()) != null) {
         s = stdInput.readLine();
         stdOut.write(pswd.getBytes());          
         stdOut.flush();
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
    System.out.println(s);
    stdOut.close();
    stdInput.close();
    stdError.close();
    System.exit(0);
    catch (IOException e) {
    System.out.println("exceptions caught: ");
    e.printStackTrace();
    System.exit(-1);

    There are only about 9 billion responses a day on how to do this. Use the search feature.

  • Complines in eclise but not through unix terminal

    Hey everybody,
    I can run my program in Eclipse but when i try and run it through the unix terminal. Everything is find in eclipse but when i try and compile it through the unix terminal, i get this error:
    "Syntax error, parameterized types are only available if source level is 5.0"
    I don't think my compiler compliance level is set in unix correctly.
    when i type in java -fullversion i get
    java full version "1.6.0-b09"
    Any ideas?

    killesk wrote:
    Any ideas?Mixed JRE and JDK, whence a difference between the version of the java executable and the one of the javac executable on your $PATH?

  • How can i use Unix database in java?

    How can i use Unix database in Java?
    Message was edited by:
    JPro

    I have not a clue about FoxPro, but the db then is FoxPro and not Unix. The better question would be "How do I connect to FoxPro DB running on Unix with JDBC?".
    My answer to that would be, search the Internet for a JDBC driver.

  • How to execute unix command in java  or jsp

    have a peace day,
    please send some sample code for
    "execute the unix command in java or jsp"
    thank you
    regards
    rex

    i execute this coding
    its compiling. while running i get the error " java.io.IOException: CreateProcess: \ls-l error=2 "
    import java.io.*;
    import java.util.*;
    public class Test
       public static void main(String[] args) throws Exception
         try
              String[] cmd = {"/ls-l"};
    Runtime.getRuntime().exec(cmd);
         catch (Exception e)
               System.out.println(e);
      }what can i do for that
    thank u

  • Unix scripting in java

    hello
    im new to java.
    and i need to learn unix scripting in java. is it difficult to learn? can one learn it within a short span of time?! could anyone please give me some links where i can learn.
    tks

    I run UNIX systems, what do you mean by Java scripting?
    do you mean SH, BASH, TCSH, CSH shells and stuff? cause Java is platform independant?
    btw, are you using Linux or FreeBSD?
    p.s. Go FreeBSD!!

  • Execute unix command using java

    Hello
    Can we execute a unix command using java? If it is how we can execute. Is this affect the performance of the program.
    Thanks

    I tried what you said. But its not working and returning error message,
    java.io.IOException: CreateProcess: ls -a error=2
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
    If i try this statement,
    Runtime.getRuntime().exec("c\windows\notepad");
    It is working fine.
    Any idea about this.
    Plz ...........

  • Problem in executing a unix command through java

    hi
    i'm trying to execute unix command through java
    simple shell command like "ls -l >test " but i'm not able to see the result.
    there are no error messages.
    Code is:
    import java.lang.Runtime.*;
    class ExecDemo
         public static void main(String[] args)
              Runtime r=Runtime.getRuntime();
              Process p=null;
              try
                   p=r.exec("ls -l > test");
              catch (Exception e)
                   System.out.println("Error executing nedit.");
    }can anyone help please.

    get the the inputStream of the runtime object after executing the command.
    now use the readLine() function until it becomes null.
    egs: with reference to ur code.
    InputStream is=p.getInputStream()
    while(is!=null)
    String s=is.readLine();
    if the command don't execute try giving the full path also like /sbin/ls -l

  • Execute unix commands from Java

    Hi,
    I have a client application running on windows. This client should connect to a unix server and check for the existence of a file and display the result as "File found/File not found". In order to connect from windows to the unix server, I used the sockets and the connection is successfully established. The second part is to check for the presence of the file in unix server. I searched in google.com and the option I found to execute a unix command from java is the "Runtime.exec()". Runtime.exec is considered as the less effective (not a favorable) one.
    Is there any other option available (other than the Runtime) to execute the unix command from java? Can you please let me know.
    Thanks a lot
    Aishu

    So, please let me know how I can execute the above unix commands without Runtime.exec()You have a client and a server.
    You want something to run on the server, not the client.
    That means that something must in fact being running on the server before the client does anything at all.
    For example telnet. Or a J2EE server application.
    So is something like that running?
    If not then there absolutely no way to do what you want, even with Runtime.exec().
    If yes then what you do depends on what is running. So Runtime.exec() would be pointless if a J2EE server was running.

  • Run a UNIX Script from java

    Hi,
    how can i run a unix script from java application. This java application is on windows.
    How can i do this.
    thanks,

    Hi,
    how can i run a unix script from java application.
    This java application is on windows.
    So I think it's safe to assume that the target script is on a remote unix server.
    Take a look at http://sourceforge.net/projects/sshtools/

  • Excute unix script from java.

    Hi need to excute unix script from java application.
    My code is:
    public class Test
    public static void main(String args[])
         try{
         p = Runtime.getRuntime().exec("./qfe0"); //qfe0 is the name of the script.
    p.waitFor();
    catch(Exception e)
    e.printStackTrace();
    My problem is that using the waitFor() statement stuck the the script. if i don't use the waitFor() it works good but then i don't know when the script is finished.
    Any idea?

    The problem is likely to be that you script is either waiting for input or has filled the stdout buffer and you are not emptying it. Search this forum for this as its been answered many times before.

  • How execute Unix script from java?

    Can I execute Unix script from java?

    Yes. Using ProcessBuilder. And read [When Runtime.exec() wont|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. It's old, but pretty much all of it is still true.

  • Sourcing UNIX Classpath in Java code

    Hi All,
    I was wondering where I could find a sample of how I can source the CLASSPATH value in UNIX in a java program.
    I want to write a program that can retrieve the value of the CLASSPATH or any other UNIX variable.
    If I set something like export $LOG=/mydirectory/log/
    How could my program retrieve the $LOG file.
    Thanks

    For just the classpath, there's a system property, as in:
    String path = System.getProperty("java.class.path");I believe. Check the API to confirm.

  • Invoking Unix command with java stored procedure

    Hi,
    I have a perfectly working environment and now I am trying to replicate the same in another server. I have a java stored procedure which invokes the Unix command using java Runtime.exec() in my code named "run". I am sure that the code is called and the java class run is resolved in oracle as I could see that in dba_java_resolvers dictionary. But I am not sure whether the function in java is called or whether a exception is thrown. how to identify this? Could there be any thing to do with settings in oracle side? please help me.
    Thanks in advance,
    Marutha

    Hi,
    Do you get any output while running the code?
    I'm testing similar solution and if there are any errors or Oracle can't execute the program due to permissions or other issues the error information will be displayed. Also in the Java class itself you need to catch exceptions and print stack trace to standard output.
    declare
    x number;
    begin
    dbms_output.enable(1000000);
    dbms_java.set_output(1000000);
    x:=system_command.run_command('testconnect.sh');
    dbms_output.put_line('Returned value='||x);
    exception
    when others then dbms_output.put_line('Sql error='||substr(sqlerrm,1,250));
    end;
    <system_command.run_command> - replace with a call to your java stored procedure.

Maybe you are looking for

  • Time machine stuck in time "long ago and far away"....

    Strange issue I came across today: After a reboot following a hard disc repair (Drive Genius 3) my MacPro is stuck in a time slot of several months ago. All time machine backups (even of yesterday's date stamp) just take me back even further in time.

  • IMovie: Event Library Disappears and Projects are Not Editable...

    Was in the middle of editing an iMovie project when it froze. Restarted the application and now there is no list under Project Library, and I can't click on the Event Library. I can see that the video is still there because it plays when I hit the sp

  • Using 2 internal HD's

    On my G5 Dual 2.5 with OS 10.5.1 startup on the 160gig HD....I have just added a 500gig internal HD (465gig actual) and it is desk mounted. I want to keep the OS and all my applications on the 160gig HD and all my files/docs (lots of music files) on

  • Adobe creative suite 4 web standard cd corrupted

    my adobe web standard 4 cd is corrupted it has student licensing attempted to install on new pc and cannot what can I do about this?

  • Is there any text books for LSMW

    Hi pls let me know is there any text books for LSMW and pls send me any soft copies of books or documets on LSMW pls ASAP thanks in advance