Running Interactive commands in java and displaying the output.

Hi All,
I'm running a sample code to execute a user defined command (cmd1) and display the results. The output of the command when executed in command prompt is
(1) Executing the command cmd1
(2) Do you want to continue(Y/N)_ <waits for user input>
(3) Based on user input
(Y) Displays the results
(N) Interrupted
But i'm facing problem when i execute the below code. When the results are being displayed instead of displaying line(1) and (2) and then waiting for the input- the code waits for the input and then only displays the results.
O/p
inside output
inside input
y (------ gets the input and then only displays the results).
Executing the command cmd1
Do you want to continue(Y/N)
results
Please help out how to resolve this issue.
Thanks.
Sample Code for reference.
import java.util.*;
import java.io.*;
public class SampleCheck {
     public static void main(String[] args) throws Exception {
          (new SampleCheck()).test();
     void test() throws Exception {
          Process proc = Runtime.getRuntime().exec("cmd1");
          // any error from the process?
          StreamHandlerErr errorStream = new StreamHandlerErr(proc
                    .getErrorStream(), System.err);
          // any output from the process?
          StreamHandlerOutput outputStream = new StreamHandlerOutput(proc
                    .getInputStream(), null);
          // any input to the process?
          // FileInputStream fin = new FileInputStream(new File("textfile1.txt"));
          StreamHandlerInput inputStream = new StreamHandlerInput(System.in, proc
                    .getOutputStream());
          // start the stream threads
          // errorStream.start();
          outputStream.start();
          inputStream.start();
          // wait till it returns
          int exitVal = proc.waitFor();
          System.exit(exitVal);
     class StreamHandlerInput extends Thread {
          InputStream is;
          OutputStream os;
          StreamHandlerInput(InputStream is, OutputStream os) {
               this.is = is;
               this.os = os;
          public void run() {
               System.out.println("inside input");
               try {
                    int c;
                    while ((c = is.read()) != -1) {
                         os.write(c);
                         System.out.println("c= " + c);
                         os.flush();
               } catch (IOException e) {
               System.out.println("End of Run Method..Input");
     class StreamHandlerOutput extends Thread {
          InputStream is;
          OutputStream os;
          File f=new File("jbsrt_output.txt");
          StreamHandlerOutput(InputStream is, OutputStream os) {
               this.is = is;
               this.os = os;
          public void run() {
               System.out.println("inside output");
               try {
                    int c;
                    FileOutputStream fs=new FileOutputStream(f);
                    /*PrintStream ps =new PrintStream(;
                    ps.print(arg0)
                    ps.close();*/
                    InputStreamReader ir = new InputStreamReader(is);
                    //System.out.println(ir.read());
                    BufferedReader br = new BufferedReader(ir);
                    String line = null;
                    while((line=br.readLine())!=null)
                         System.out.println(line);
               } catch (Exception e) {
               System.out.println("End of Run Method..Output");
     class StreamHandlerErr extends Thread {
          InputStream is;
          OutputStream os;
          StreamHandlerErr(InputStream is, OutputStream os) {
               this.is = is;
               this.os = os;
          public void run() {
               System.out.println("inside Err");
               try {
                    int c;
                    while ((c = is.read()) != -1) {
                         os.write(c);
                         os.flush();
               } catch (IOException e) {
               System.out.println("End of Run Method..Err");
}

Console input is line buffered. This means you only get the first character a line after the newline has been inputed.
The same thing happen if you just type on the console.
I am not aware of any simple way around this.
IDEs get around this by changing the application run so that the input/output is captured as it happens and sent over a socket connection.

Similar Messages

  • // Code Help need .. in Reading CSV file and display the Output.

    Hi All,
    I am a new Bee in code and started learning code, I have stared with Console application and need your advice and suggestion.
    I want to write a code which read the input from the CSV file and display the output in console application combination of first name and lastname append with the name of the collage in village
    The example of CSV file is 
    Firstname,LastName
    Happy,Coding
    Learn,C#
    I want to display the output as
    HappyCodingXYZCollage
    LearnC#XYXCollage
    The below is the code I have tried so far.
     // .Reading a CSV
                var reader = new StreamReader(File.OpenRead(@"D:\Users\RajaVill\Desktop\C#\input.csv"));
                List<string> listA = new List<string>();
                            while (!reader.EndOfStream)
                    var line = reader.ReadLine();
                    string[] values = line.Split(',');
                    listA.Add(values[0]);
                    listA.Add(values[1]);
                    listA.Add(values[2]);          
                    // listB.Add(values[1]);
                foreach (string str in listA)
                    //StreamWriter writer = new StreamWriter(File.OpenWrite(@"D:\\suman.txt"));
                    Console.WriteLine("the value is {0}", str);
                    Console.ReadLine();
    Kindly advice and let me know, How to read the column header of the CSV file. so I can apply my logic the display combination of firstname,lastname and name of the collage
    Best Regards,
    Raja Village Sync
    Beginer Coder

    Very simple example:
    var column1 = new List<string>();
    var column2 = new List<string>();
    using (var rd = new StreamReader("filename.csv"))
    while (!rd.EndOfStream)
    var splits = rd.ReadLine().Split(';');
    column1.Add(splits[0]);
    column2.Add(splits[1]);
    // print column1
    Console.WriteLine("Column 1:");
    foreach (var element in column1)
    Console.WriteLine(element);
    // print column2
    Console.WriteLine("Column 2:");
    foreach (var element in column2)
    Console.WriteLine(element);
    Mark as answer or vote as helpful if you find it useful | Ammar Zaied [MCP]

  • How to run commands like "ipconfig" and get the output in adobe AIR in windows?

    import flash.desktop.NativeProcess; 
    import flash.desktop.NativeProcessStartupInfo;   
    if (NativeProcess.isSupported) {     
         var npsi:NativeProcessStartupInfo = new NativeProcessStartupInfo();     
         var processpath:File = File.applicationDirectory.resolvePath("MyApplication.whatever");     
         var process:NativeProcess = new NativeProcess();       
         npsi.executable = processpath;     
         process.start(npsi); 
    The above can only run a sub-application, but how to run an independent  application(command) like ipconfig and get the result?

    Hi,
    here is an example of running a net Use command line from AIR, unig the new NativeProcess. Hope it will help !
    function launchProcess()
      var file = air.File.applicationDirectory;
      // set command path
      file = file.resolvePath("C:/Windows/system32/net.exe");
      var nativeProcessStartupInfo = new air.NativeProcessStartupInfo();
      nativeProcessStartupInfo.executable = file;
      // prepare command parameters
      var args = new runtime.Vector["<String>"]();
      args.push('USE');
      args.push('W:');
      args.push('/delete');
      args.push('/y');
      // set arguments
      nativeProcessStartupInfo.arguments = args;
      // add listeners to catch command outputs
      process.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
      process.addEventListener(air.ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
      process.addEventListener(air.NativeProcessExitEvent.EXIT, onExit);
      // create and run Native process
      process = new air.NativeProcess();
      process.start(nativeProcessStartupInfo);
    function onOutputData(ProgressEvent)
      var processResults = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
      air.trace("Results: \n" + processResults);
    function onErrorData(ProgressEvent)
      var processResults = process.standardError.readUTFBytes(process.standardError.bytesAvailable);
      if(processResults.search('password') > -1){
        window.alert('Bad password');
      air.trace("Errors: \n" + processResults);
    function onExit(NativeProcessExitEvent)
      air.trace("Process ended with code: " + NativeProcessExitEvent.exitCode);

  • Running ls command from Java stroed procedure no output

    Hi ,
    I am trying to run ls command from java stored procedure in oracle
    Process p = Runtime.getRuntime().exec("ls");
    BufferedReader stdInput = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new
    InputStreamReader(p.getErrorStream()));
    // read the output from the command
    System.out.println("output of the command run:\n");
    while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
    from java stored procedure in oracle.
    i get output of println statments but it does not go into while loop to print from stdInput.
    Result of running Java stored procedure is -
    output of the command run:
    Call completed.
    when i run the program on client side it works fine.
    Has anybody tried this from java stroed procedure.
    Thanks,
    Jag

    Jag,
    Actually, the question of whether it works for me seems to depend on the version of the OS (or Oracle). On RedHat Linux (Oracle 8.1.6) it didn't work at all, but on Solaris (Oracle 9.0.2) it did. Here's the output from that run:
    SQL> /
    output of the command run:
    init.ora
    initDBPart9i.DBPSun01.ora
    initdw.ora
    lkDBPART9I
    orapw
    orapwDBPart9i
    spfileDBPart9i.ora
    Done
    PL/SQL procedure successfully completed.
    But, I did need to change a line of your code to this:
    Process p = Runtime.getRuntime().exec("/usr/bin/ls");
    your original was:
    Process p = Runtime.getRuntime().exec("ls");
    You might consider, if possible, use of some of the Java File classes instead of ls, as this might make things more predictable for you. There were some examples in oramag.com a few months ago, but they were pretty simple (you might not need them).
    Hope this helps,
    -Dan
    http://www.compuware.com/products/devpartner/db/oracle_debug.htm
    Debug PL/SQL and Java in the Oracle Database

  • Run Clear Case command from java and save the out put in to a file.

    Can any one help me out ...
    I want to execute Clear case command from a java and want to save the out put of this command to a file.
    I am naot able to find out how to start..
    Message was edited by:
    chandra_verma

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Running ssh command from java and then answering password prompt

    Hi,
    I have a situation that has not solved yet. I am running ssh command from unix terminal without any problem, and then i enter password.
    For example :
    [oracle@fuata]:/export/home/oracle> ssh -N [email protected] -L 9901:127.0.0.1:9999
    Password:
    It is working. I have question that how can i perform this in java? I am thinking that i can run ssh command by using Runtime Class, it is ok. But how can i answer the password? I am a bit confused. Is there any example looks like this?
    Thanks for responses.

    futi wrote:
    Thanx. Firstly i insisted to do this without jsch but actually this is harder than jsch. I edit some of code pieces PortForwardingL.java and could run it. It works problem-free. Could you say why you "insisted" on this approach. It can't be for speed+ since jsch is very fast. It can't be for portability+ since jsch is portable but the use of Runtime.exec() requires the installation of ssh software. It can't be because of limitations+ since jsch is a fully featured library. It can't be for security+ since jsch is secure. It can't be for ease of use+ since jsch is much easier to use than ssh with Runtime.exec(). Unless it's a licensing issue, it can't be for commercial+ reasons since jsch is free. The only reason I can think of why one would "insisted" on this approach is if it is for some college project.

  • Need to run a sql query in the background and display the output in HTML

    Hi Guys,
    I have a link in my iprocurement webpage, when i click this link, a query (sql query) should be run and the output should be displayed in a HTML page. Any ideas of how this can be done. Help appreciated.
    We dont have OA Framework and we r using 11.5.7.
    help needed
    thanx

    Read Metalink Note 275880.1 which has the link to developer guide and personalization guide.

  • Add text item data and display the output in another text item

    Hi! All,
    I have four text item. like HA,DA,basic_salary and total_sal.I want to add the data entered in the text item in HA,DA,basic_salary and display in total_sal text item.How can I do this.Please help in this matter.
    Thanks,
    Abha

    1.Select the text item TOTAL_SAL
    2.Open property palette
    3.Under Calculation node
         Set calculation mode as Formula
         Set Formula as nvl(:ha,0)+nvl(:da,0)+nvl(:basic_salary,0)                                                                                                                                                                                                                                                                                                                                                                                               

  • How to report print to the printer immediately and display the popup?

    Dear friends,
    I am running my report in background and displaying the confirm results on popup window and sending the results to printer,
    but now i want to send the results page to printer then  want to display the popup.
    i have writen my popup perform after printer perform only but its not working...when i am clossing the popup or came back from that popup then only the results sending to printer...
    How to report print to the printer immediately and display the popup?
    Thanks in advance
    Sridhar

    Hi Sudheer,
    I am using my print parameters like this :
        NEW-PAGE PRINT ON DESTINATION ws_printer
                             IMMEDIATELY 'X'
                             KEEP IN SPOOL 'X'
                             NEW LIST IDENTIFICATION 'X'
                             SAP COVER PAGE 'X'
                             ARCHIVE MODE '1'
                             LINE-COUNT 64
                             LINE-SIZE 170
                             NEW-SECTION
                             NO DIALOG.
    Then also its not printing immediatly.
    here one thing for displaying the popup i am using submit report(calling another report for popup purpose)
    before trigering the submit programe i need to print this.
    Thanks
    Sridhar.

  • How to write code to print and save the output in my GUI?

    I had been searching on code to program print and save commands to print and save the output from the GUI but to no avail. Can someone help me?

    The output will be link from the previous GUI page. Hence the output is a page with Jtable and a button for print to print the information in the JTable.

  • Way to display the output of tail command in a Java app

    Hi,
    I have a Java app running in the Linux environment. The Weblogic outputs get written to a log. I would like to design a screen in my app that will enable me to monitor my logs. I normally log into the Linux machine and do a tail -f on the log.
    tail -f Managed_1.logI would like to run this tail -f command from my Java app so that I am able to view the log proress from my app itself. I know we can use Runtime to run external programs but this is a case where a command will be executed continuously and the output will need to be displayed in my app, more specifically on a JSP.
    Any ideas would be most appreciated.
    Thanks and regards,
    Ganesh

    I had a look at the API for the Process class which
    lists an abstract method called getOutputStream().
    What I am not clear is that the documentation says
    that the exec method of Runtime will return an
    instance of a subclass of Process. Does this mean
    that the getOutputStream() method would have already
    been coded for the subclass instance returned?Yes.
    And even if we do get the OutputStream from the tail
    -f process, we will still have to read and display
    the info on a line by line basis. Will this happend
    to be fast enough to macth atleast to some extent the
    speed at which the log is written to?There are two ways to answer this:
    1. Ask somebody who knows how fast the log is written to.
    2. Try it and see.
    My approach would be the second option.

  • Having trouble in running a unix command and getting the output

    Hi,
    I am trying to run a unix command from within the java code. I am not able to make it work. I am enclosing the code and the error message that I am getting. Any help is highly appreciated.
    import java.io.*;
    public class RunCommand {
        public static void main(String args[]) {
            String s = null;
            try {
                Process p = Runtime.getRuntime().exec("cat UNIX_ASCII_TEXT_FILE | A_UNIX_PROGRAM -d");
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                // read the output from the command
                System.out.println("Here is the standard output of the command:\n");
                while ((s = stdInput.readLine()) != null) {
                    System.out.println(s);
                // read any errors from the attempted command
                System.out.println("Here is the standard error of the command (if any):\n");
                while ((s = stdError.readLine()) != null) {
                    System.out.println(s);
                System.exit(0);
            catch (IOException e) {
                System.out.println("exception happened - here's what I know: ");
                e.printStackTrace();
                System.exit(-1);
    }The error message that I am getting is
    Here is the standard output of the command:
    SLu|%%$$=
    Here is the standard error of the command (if any):
    cat: cannot open |
    cat: cannot open A_UNIX_PROGRAM
    cat: cannot open -dLooks like the cat command is working and not the pipe command and the command after the pipe. But when I run the UNIX command from the command prompt I get the expected result.

    You might read this article and see if its approach works.
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Command to display only the latest modified directory within another directory and display the date of the last modify

    Okay I want to be able to run a .cmd file from my workstation to query a certain folder on remote clients. I want the command to find the specific folder within another folder and display the current date modified of that folder. I was
    able to use a command prompt to list the subdirectory that I was looking for on a specific computer by using the
    DIR command. It was something like this:
    dir C:\ParentFolder\ChildFolder /ad /o-d /b
    This shows a list of directories within the "ChildFolder" directory. The output would be something like:
    dir C:\ParentFolder\ChildFolder /ad /o-d /b
    folder1
    folder2
    folder3
    folder4
    So what I need now is a way to just show the folder in this group that had the most recent modification. For example if "folder2" was the most recently modified folder in the group, I would like my command line to just display "folder2 04/08/14
    04:13 PM
    Any help would be greatly appreciated.
    Cheers!

    Thanks Mike! This is what I was looking for! Much appreciated!
    I would like to run this as a script from my admin workstation that will query clients that have the "ChildFolder" directory. Is there a way to output the results to a .log/.txt file? I was working on .cmd that looked like this:
    {REM Verify current folder on remote clients
    del current-folder.log
    ECHO WorkStation-1 >> CurrentFolder/current-folder.log 2>&1
    ECHO ---------------- >> CurrentFolder/current-folder.log 2>&1
    DIR \\WorkStation-1\C$\ParentFolder\ChildFolder /ad /o-d /b >> CurrentFolder/current-folder.log 2>&1
    ECHO ---------------- >> CurrentFolder/current-folder.log 2>&1}
    My results looked something like this:
    " WorkStation-1
    Folder1
    Folder2
    Folder3
    I know it's ugly, but it was working (somewhat). I just needed to list only the most recently modified folder. Anyway, I've rambled enough.
    Is there a way to get my desired results using the PS command that you provided me?

  • I am trying to build a basic TCL skeleton script that reads a remote SNMP OID and displays the value on the screen.

    I am trying to build a basic TCL skeleton script that reads a remote SNMP OID and displays the value on the screen.
    I don't want it to be an EEM Event, I just want to run it from the (tcl)# prompt.
    So I guess I'm asking if you can use cli_exec and other commands in the "namespace import ::cisco::eem::*" in a normal non-EEM script - can I do that?
    This is the error I get:
    OTN.159(tcl)#source flash:TCL_SNMP_Remote_Read.tcl
    invalid command name "::cisco::eem::event_register_none"             ^
    % Invalid input detected at '^' marker.
    What am I missing?
    =================  TCL_SNMP_Remote_Read.tcl  ==============================
    ::cisco::eem::event_register_none
    namespace import ::cisco::eem::*
    namespace import ::cisco::lib::*
    if [catch {cli_open} RESULT]
        { error $RESULT $errorInfo }
        else { array set cli1 $RESULT }
    if [catch {cli_exec $cli1(fd) "snmp get v2c 192.168.1.100 public timeout 1 oid 1.3.6.1.2.1.1.1.0" } RESULT]
           { error $RESULT $errorInfo  }
           else { set SnmpSysDesc $RESULT }
    if [catch {cli_close $cli1(fd) $cli1(tty_id)} RESULT] {
                error $RESULT $errorInfo
    puts $SnmpSysDesc
    =========================================================================
    In the sho-run config I have:
    event manager directory user policy "flash:/"
    event manager session cli username "cisco"
    Any help to get me started would be greatly appreciated!
    Tim

    If you don't want an EEM policy, then don't use any of the EEM constructs.  Instead, all you need is this:
    set output [exec "snmp get v2c 192.168.1.100 public timeout 1 oid 1.3.6.1.2.1.1.1.0"]puts $output

  • Want to open a new browser window and display the html file in locale disk.

    Hi,
    I want to open a new browser window and display the html file in local drive. The below html applet work in local system successfully. But i deploy the same in web server (Tomcat) and try the same in client machine it does not work. Please help.
    Note:
    The class below fileopen.FileOpen.class i make it as a jar and put it in jre\ext folder at the client machine.
    ------------------------------------FileOpen.html(Tomcat)-----------------------------------------------------
    <html>
    <body >
    <applet code="OpenFile.class" archive="loadfile.jar" width="100" height="100">
    <param name="path" value="file://c:/open.html" />
    </applet>
    </body>
    </html>
    -------------OpenFile.java in server(Tomcat)--------------------------------------------
    public class OpenFile extends Applet implements ActionListener{
    String path = "";
    fileopen.FileOpen open = null;
    Button b = null;
    public void init(){
    path = getParameter("path");
    b = new Button("Open");
    b.addActionListener(this);
    add(b);
    public void actionPerformed(ActionEvent ae){
    try
    open = new fileopen.FileOpen(this,path);
    catch (Exception e){
    e.printStackTrace();
    -------------------------------------------FileOpen.java /Client JRE/ext----------------------------------------------------
    package fileopen;
    public class FileOpen
    AppletContext context = null;
    URL url = null;
    public FileOpen(Applet applet,String path)
    try
    if(null != applet){
    context = applet.getAppletContext();
    if (null != path)
    url = new URL(path);
    context.showDocument(url, "_blank");
    }catch(Exception ex)
    ex.printStackTrace();
    Please help to solve this issue very urgent.
    Thanks in advance.
    By,
    Saravanan.K.

    zzsara wrote:
    I want to open a new browser window and display the html file in local drive. ...Did you ever pause to consider how ridiculous that is?
    The best audience for applets is people off the internet. 'People off the internet' might be using a computer that has no (what was it?) 'open.html' in the root of the C: drive. In fact (shock horror) they may not even be running Windows, and would therefore probably have no 'C:' drive at all.
    If you do not intend to distribute this to people off the web, an application makes a lot more sense, but even then, you cannot rely on the document being there unless you 'put it there' (during installation, for instance).
    As the other poster intimated, applets can load documents off the local disk as long as they are trusted. Here is an example*, but note that it is not so rash as to presume any particular path or file, and instead leaves it to the user to choose the document to display.
    * The short code can be seen at SDNShare on the [Defensive Loading of Trusted Applets|http://sdnshare.sun.com/view.jsp?id=2315] post.
    On the other hand, a sandboxed applet can load any document coming from its own server via URL, or get showDocument(URL) to work. In that case, the JRE must recognize that the URL is from its own server, so the best way to form URLs for applet use is via the URL constructor
    new URL(getDocumentBase(), "path/to/open.html");That is how I form the URL in this [ sandboxed example of formatting source|http://pscode.org/fmt/sbx.html?url=/jh%2FHelpSetter.java&col=2&fnt=2&tab=2&ln=0]. Of course, in this case the applet loads the document, then parses the text to draw the formatted version, but the point is that an URL produced this way will work with showDocument(URL).
    I am pretty sure showDocument() in an applet off the internet will work with an URL pointing to a foreign (not its own) server, but it will not be able to load documents off the end user's local disks.
    I suggest a couple of things.
    - Try to express this problem in terms of what feature it is that you want to offer the end user. Your question jumps directly to a bad strategy for achieving ..who knows what? An example of a feature is "Shows the applet 'help' files on pressing F1".
    - A good way to indicate interest in a solution is to offer [Duke stars|http://wikis.sun.com/display/SunForums/Duke+Stars+Program+Overview] to match that interest.
    Edit 1:
    ..and please figure out how to use the CODE tags.
    Edited by: AndrewThompson64 on Sep 12, 2008 11:14 PM

Maybe you are looking for

  • Problem setting Index value on ComboBox

    I am running into a problem with setting the index on a dropdown box. I will try to give as much detail as possible. From what I can tell, it should be working and does, but only for one item. If anyone can suggest a different group to post to, let m

  • Windows Server 2008 R2 AD recovery

    I have a 2008 R2 Domain Controller that was running Exchange 2010 that I recently ran windows updates on (4 months worth) and afterword it would no longer boot.  It would get to the point were you could see the cursor and then just restart.  I tried

  • Post goods receipt problem of customer returns material

    hi, i have a problem while doing customer returns  in VL01N (PGR).system displays error msg. E VL 171 Status of inpection lot xxxxxxx / partial lot 00000 does not allow goods issue. Material having inspection set up on material master with inspection

  • Can't connect new MacBook to wireless internet

    Just bought a MacBook, but I can't get it to connect to the internet over my wireless network. It picks up the signal, I typed in the password, and Internet Connect says that I am connected. But when I open Safari it just tells me I am not connected.

  • Unable to change modifier keys on exernal keyboard.

    Running a unibody MBP with 10.8.5.  Trying to change the modifier keys (swap Option and Command) on an external USB keyboard (daskeyboard ultimate stealth).  Using Preferences -> Keyboard/Mouse -> Modifier Keys, I select my external keyboard (listed