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
Inner class and Anonymous class
Inner class: classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private.

Anonymous class: Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
Famous Quotations
Be yourself; everyone else is already taken.
-- Oscar Wilde

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.