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
Different types of Access Modifiers
public: Any thing declared as public can be accessed from anywhere.

private: Any thing declared as private can't be seen outside of its class.

protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.

default modifier: Can be accessed only to classes in the same package.
Famous Quotations
Insanity: doing the same thing over and over again and expecting different results.
-- Albert Einstein

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.