How can I get all errors when executing a command?

icortazar :

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

This 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 that there are more than one errors, so I expect more than one output but as you can see in the photo I get only one. enter image description here

SylarBenes :

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

From Oracle's documentation of ProcessBuilder class:

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 example's I have seen use Redirect.appendTo(File file) rather than Redirect.to(file). The documentation may explain why.

From Oracle's documentation of ProcessBuilder.Redirect :

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 would try replacing

pb.redirectError(errorsFile) 

with

pb.redirectError(Redirect.appendTo(errorsFile))

and see if you get more lines that way.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=97416&siteId=1