tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > IO > External Process Input Output

External Process Input Output 

The following example shows how to read the output from and write the input to external process. This process could be a DOS Batch script process, VB script process or any other process. Please note that the Batch process's input stream becomes output and output stream becomes input for your java program.

File Name  :  
com/bethecoder/tutorials/io/ExternalProcInputOutput.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class ExternalProcInputOutput {

  /**
   @param args
   */
  public static void main(String[] args) {

    String line;
    try {
      Process proc = Runtime.getRuntime().exec("C:\\ex_proc_in_out.bat");
      BufferedReader procInput = new BufferedReader(
          new InputStreamReader(proc.getInputStream()));
      
      BufferedWriter procOutput = new BufferedWriter(
          new OutputStreamWriter(proc.getOutputStream()));
      
      //Give input to batch process
      procOutput.write("KV");
      procOutput.flush();
      
      //Read output from batch process
      line = procInput.readLine();
      System.out.println("-->" + line);
      
      //Give input to batch process
      procOutput.write("Sudhakar");
      procOutput.flush();

      //Read output from batch process
      while ((line = procInput.readLine()) != null) {
        System.out.println("->" + line);
      }
      
      procOutput.close();
      procInput.close();
      
    catch (Exception e) {
      e.printStackTrace();
    }
  }
  
}
   

The DOS Batch file referred is shown below,
File Name  :  
source/com/bethecoder/tutorials/io/ex_proc_in_out.bat 
@echo off 
set FNAME=
set /P FNAME=Enter your first name:
echo.
echo Welcome %FNAME%


set LNAME=
set /P LNAME=Enter your last name:
echo.
echo Welcome %LNAME%

It gives the following output,
-->Enter your first name:
->Welcome KV
->Enter your last name:
->Welcome Sudhakar



 
  


  
bl  br