Share this page 

Capture the output from a VBSTag(s): IO


This HowTo query the Windows Registry for a specific key. The VBS prints the result and from Java, we capture this output.

Since we need the output, we must use the VBS interpreter for the console mode (CSCRIPT.EXE).

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;

public class VBSUtils {
  private VBSUtils() {  }

  public static String readWindowRegistry(String key) {
    String result = "";
    try {

        File file = File.createTempFile("realhowto",".vbs");
        file.deleteOnExit();
        FileWriter fw = new java.io.FileWriter(file);

        String vbs = "Dim WSHShell \n"
                   + "Set WSHShell = WScript.CreateObject(\"WScript.Shell\") \n"
                   + "WScript.Echo _ \n"
                   + "WSHShell.RegRead(\"" + key + "\") \n"
                   + "Set WSHShell = Nothing \n";
        fw.write(vbs);
        fw.close();
        Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
        BufferedReader input =
            new BufferedReader
              (new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = input.readLine()) != null) {
            result += line;
        }
        input.close();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return result.trim();
  }



  public static void main(String[] args){
    //
    // DEMO
    //
    String result = "";
    msgBox("Get the path of Acrobat reader from the registry");
    result = readWindowRegistry
      ("HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcroRd32.exe\\");
    msgBox("Acrobat Reader is located in " + result);
  }

  public static void msgBox(String msg) {
    javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
       null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION);
  }
}