Tofetopo Tofetopo - 1 year ago 113
Java Question

Java application not reading from file when executing command with Runtime.getRuntime()

I have a Java app that executes a command using Runtime.getRuntime.exec("command"); Then it generates a file which I need to read to find a string, everything ok so far. The problem is that the program can't find a given string after executing the command, but if I comment out the line Runtime.getRuntime.exec("command"); after I run the app the first time and further runs and the file is created it finds the string properly. Seems like getRuntime() is stopping from work the fileReader for some reason. Anyone knows a fix for this?

public static void main(String[] args) throws IOException{

String[] command = new String[3];
command[0] = "cmd.exe";
command[1] = "/c";
command[2] = "C:\\Users\\kjdah\\Desktop\\handle.exe -a > C:\\Users\\kjdah\\Desktop\\handles.txt";


String toFind = "##?#USB#VID_04F2&PID_B2E1&MI_00#6&9f9977c&0&0000#";
File file = new File("C:\\Users\\kjdah\\Desktop\\handles.txt");

boolean found = false;
String strLinePid = null;

try {
FileReader fstream = new FileReader(file);
BufferedReader buffer = new BufferedReader(fstream);
String strLine;

while ((strLine = buffer.readLine()) != null) {

strLinePid = strLine;

found = true;


catch (Exception e){
System.err.println("An error happened: " + e.getMessage());


Answer Source

Runtime.exec creates a new process that runs concurrently. You have to wait for it to finish for processing it's result.

This can be done with the method waitFor of the Process that exec returns. Additionally, it is a good idea to check if the process was successful. Have a look at the Javadoc of Process for more information.