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
Stream and types of Streams
A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are:

Byte Streams: Provide a convenient means for handling input and output of bytes. Byte Streams classes are defined by using two abstract classes, namely InputStream and OutputStream.

Character Streams: Provide a convenient means for handling input & output of characters. Character Streams classes are defined by using two abstract classes, namely Reader and Writer.
Famous Quotations
Education is what remains after one has forgotten what one has learned in school.
-- 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.