JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Program: How to run operating system specific command and read its output?


Description:

Below example shows how to run operating specific command and read its output. ProcessBuilder class can helps you to run any commands.


Code:
package com.java2novice.processbuilder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyOsCommandRun {

	public static void main(String a[]){
		
		InputStream is = null;
		ByteArrayOutputStream baos = null;
		ProcessBuilder pb = new ProcessBuilder("ls", "-l");
		try {
			Process prs = pb.start();
			is = prs.getInputStream();
			byte[] b = new byte[1024];
			int size = 0;
			baos = new ByteArrayOutputStream();
			while((size = is.read(b)) != -1){
				baos.write(b, 0, size);
			}
			System.out.println(new String(baos.toByteArray()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				if(is != null) is.close();
				if(baos != null) baos.close();
			} catch (Exception ex){}
		}
	}
}

Output:
total 0
drwxrwxrwx  4 root  846622648  136 Aug 25 17:14 bin
drwxrwxrwx  3 root  846622648  102 Jul  5 21:22 resources
drwxrwxrwx  3 root  846622648  102 Mar 26 21:57 src
<< Previous Program | Next Program >>

List Of All ProcessBuilder Class Sample Programs:

  1. How to invoke other applicatons in java?
  2. How to run operating system specific command and read its output?
  3. How to get process environment variables in java at runtime?
  4. How to run ProcessBuilder with list of commands?
Knowledge Centre
What is daemon thread?
Daemon thread is a low priority thread. It runs intermittently in the back ground, and takes care of the garbage collection operation for the java runtime system. By calling setDaemon() method is used to create a daemon thread.
Famous Quotations
Do not confuse motion and progress. A rocking horse keeps moving but does not make any progress.
-- Alfred A. Montapert

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.