Java – How do I get all errors when executing a command?

How do I get all errors when executing a command?… here is a solution to the problem.

How do I get all errors when executing a command?

I’m developing a java program and at some point in the program I need to execute some command and display all the errors returned by that command. But I can only show the first one.

Here is my code :


String[] comando = {mql,"-c",cmd};

File errorsFile = new File("C:\\Users\\Administrator2\\Desktop\\errors.txt");

ProcessBuilder pb = new ProcessBuilder(comando);
pb.redirectError(errorsFile);

Process p = pb.start();
p.waitFor();

String r = errorsFile.getAbsolutePath();

Path ruta = Paths.get(r);
Charset charset = Charset.forName("ISO-8859-1");

List<String> fileContents = Files.readAllLines(ruta,charset);

if (fileContents.size()>0){
      int cont = 1;
      for(String str : fileContents){

System.out.println("Error"+cont);
              System.out.println("\t"+str);
              cont++;
      }
}
else{
     other code
}

In this case, I know there is more than one error, so I would like the output to be more than one, but as you can see in the photo, I only get one.
enter image description here

Solution

I think the key here may be that ProcessBuilder’s redirectError (File file) is actually redirectError (Redirect.to(file)).

ProcessBuilder class documentation from Oracle:

This is a convenience method. An invocation of the form redirectError(file) behaves in exactly the same way as the invocation redirectError (Redirect.to(file)).

Most of the examples I’ve seen use Redirect.appendTo(File file) instead of Redirect.to(file). The documentation may explain why.

ProcessBuilder.Redirect documentation from Oracle:

public static ProcessBuilder.Redirect to(File file)
Returns a redirect to write to the specified file. If the specified file exists when the subprocess is started, its previous contents will be discarded.

public static ProcessBuilder.Redirect appendTo(File file)
Returns a redirect to append to the specified file. Each write operation first advances the position to the end of the file and then writes the requested data.

I will try to replace

pb.redirectError(errorsFile) 

with

pb.redirectError(Redirect.appendTo(errorsFile))

See if you get more rows this way.

Related Problems and Solutions