import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PipedOutputStream;
import java.util.ArrayList;
import java.util.Iterator;

// Note: This example will not work on normal Windows.  You can go to
// www.cygwin.org and download the Cygwin pseudo-Linux add-on for Windows.
// Or just change it to use Windows commands, or run it on X-Windows with
// a substitute for notepad.
public class RuntimeExample {
	public static void main(String[] args) {
		Runtime runtime = Runtime.getRuntime();
		
		try {
			System.out.println("Search for a string in this directory");
			System.out.println("Please enter the string you would like to search for: ");
			BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
			String pattern = keyboard.readLine();
			
			// The command you want to execute goes here.
			Process proc = runtime.exec("grep \"" + pattern + "\" *");
			// Read in the output of the command.
			BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			String next = null;
			
			// Record all file names found.
			ArrayList<String> fileNames = new ArrayList<String>();
			while ((next = in.readLine()) != null) {
				System.out.println(next);
				int colonIndex = next.indexOf(':');
				if (colonIndex != -1) {
					String fileName = next.substring(0, colonIndex);
					if (!fileNames.contains(fileName)) {
						fileNames.add(fileName);
					}
				}
			}
			
			Iterator<String> fileLister = fileNames.iterator();
			while (fileLister.hasNext()) {
				Process noteProc = runtime.exec("notepad " + fileLister.next());
				// Optional: Wait until one notepad has closed before opening the next.
				noteProc.waitFor();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// Other random features in Runtime class...
		System.out.println("Available/Total Memory: " + runtime.freeMemory() + "/" + runtime.totalMemory());
			
		// You'll probably only have one processor.
		System.out.println("Available processors: " + runtime.availableProcessors());
	}
}

