Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7408907
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T05:59:34+00:00 2026-05-29T05:59:34+00:00

So I am writing a program in Java that needs to be able to

  • 0

So I am writing a program in Java that needs to be able to run on Windows or Linux and needs to be able to make requests to the command line such as dir or ls. It then needs to get the resultant output from these commands and AFTERWARDS prompt for another command. Here is my code:

import java.io.*;
import java.util.*;

public class myShell
{
    public static void main(String[] args)
    {
        Runtime runtime = Runtime.getRuntime();
        Process process;
        Scanner keyboard = new Scanner(System.in);
        String userInput = "";
        String osName = System.getProperty("os.name" );
        BufferedReader brStdOut = null;
        String stdOut;
        BufferedReader brErrorStream = null;
        String errorStream;

        while(userInput.compareToIgnoreCase("exit") != 0)
        {
            System.out.println();
            System.out.print("??");

            userInput = keyboard.nextLine();

            int indexOfPound = userInput.indexOf('#');
            if(indexOfPound == 0)
            {
                userInput = "";
            }
            else if(indexOfPound > 0)
            {
                userInput = userInput.substring(0, indexOfPound);
            }
            userInput = userInput.trim();

            try
            {   
                if(osName.contains("Windows"))
                {
                    process = runtime.exec("cmd /c " + userInput);
                }
                else
                {
                    process = runtime.exec(userInput);
                }

                brStdOut = new BufferedReader(new InputStreamReader(
                           process.getInputStream()));
                brErrorStream = new BufferedReader(new InputStreamReader(
                                process.getErrorStream()));

                while((stdOut = brStdOut.readLine())  != null)
                {
                    System.out.println(stdOut);
                }
                while((errorStream = brErrorStream.readLine()) != null)
                {
                    System.err.println(errorStream);
                }

                process.waitFor();
            }
            catch(Exception e)
            {
                System.out.println("Error executing: " + userInput); 
                System.out.println(e.getMessage());
            }
            try
            {
                brStdOut.close();
            }
            catch(Exception e)
            {
            }
            try
            {
                brErrorStream.close();
            }
            catch(Exception e)
            {
            }
        }
        System.exit(0);
    }
}

I should mention that I’m currently testing on a Windows 7 machine and that anything after a # on a line is considered as a comment.

When I run this, say using dir, the result comes back just fine, but try running it with ls (which gives a message saying that it’s not a recognized command in Windows) and the error stream may be printed before the next prompt (??) (which is desirable), after the next prompt, or partially before and partially after the prompt. Is there a way to consistently get the error message printing BEFORE the prompt?

Here is an example of what’s happening now:

??dir
 Volume in drive C is Windows7_OS
 Volume Serial Number is SomeNumbers

 Directory of C:\Users\BlankedOut\Documents\Java\Eclipse\Workspace\Prog1

02/05/2012  03:48 PM    <DIR>          .
02/05/2012  03:48 PM    <DIR>          ..
02/05/2012  03:48 PM               301 .classpath
02/05/2012  03:48 PM               387 .project
02/05/2012  03:48 PM    <DIR>          .settings
02/05/2012  08:39 PM    <DIR>          bin
02/05/2012  08:39 PM    <DIR>          src
               2 File(s)            688 bytes
               5 Dir(s)  861,635,362,816 bytes free

??ls

??'ls' is not recognized as an internal or external command,
operable program or batch file.
ls
'ls' is not recognized as an internal or external command,
operable program or batch file.

??exit

My other question regards when I try running a command such as date. In the DOS window, this gives a 2-line response and waits for more input, but in Java, I only get the first line of the response (although with dir I seem to get all the lines), but then after that first date line, the program just hangs… does anyone know why this might be happening?

Thanks a lot!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T05:59:34+00:00Added an answer on May 29, 2026 at 5:59 am

    When you run the ls, there is an error, and the error would be shown in both stdout and in error stream,

                    while((stdOut = brStdOut.readLine())  != null)
                    {
                        System.out.println(stdOut);
                    }
                    while((errorStream = brErrorStream.readLine()) != null)
                    {
                        System.err.println(errorStream);
                    }
    

    Because of above code block, errors are always printed after std out, so you could switch the loops to get desirable output.

    When in the date prompt, it asks for the new date, where the prompt will wait for a user input. Where your program is not giving any, so it waits there and you see it as java program got stuck.

    Edit : Try this, as this will use separate threads,

    import java.lang.*;
    import java.io.*;
    
    public class StreamGobbler implements Runnable {
        String name;
        InputStream is;
        Thread thread;
        String output="";
    
        public StreamGobbler (String name, InputStream is) {
        this.name = name;
        this.is = is;
        }
    
        public void start () {
        thread = new Thread (this);
        thread.start ();
        }
    
        public void run () {
        try {
        InputStreamReader isr = new InputStreamReader (is);
        BufferedReader br = new BufferedReader (isr);
    
           while (true) {
              String s = br.readLine ();
              if (s == null) break;
              output += s;
           }
           is.close ();
           } catch (Exception ex) {
              System.out.println ("Problem reading stream " + name + "... :" + ex);
             ex.printStackTrace ();
           }
        }
    }
    
        public class ProgA {
        public static void main(String[] args) throws Exception {
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec("execute command prompt");
        StreamGobbler s1 = new StreamGobbler ("stdin", p.getInputStream ());
        StreamGobbler s2 = new StreamGobbler ("stderr", p.getErrorStream ());
        s1.start ();
        s2.start ();
        p.waitFor();
        System.out.println(s2.output + s1.output);
        }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm writing (under linux or windows+cygwin) a java program that needs to run a
I am writing a program that needs to run a java.jar server. I need
I am writing a java program that needs a file open dialog. The file
I'm writing a program (in Java) that needs to extract links from webpages. I'm
Im writing a program that needs to be able to find the difference between
I'm currently writing a java program that requires some Data to run. The data
I'm pretty new to Java, and I'm writing a program that needs to store:
Is there any way to make a Java program (in Windows) that just acts
I am writing a JAVA program for work that at some point needs to
I'm writing a Java program MyAwesomeProgram that uses Process' exec function to run bash

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.