I have this code:
try {
// Create a temporary file
Path tmpFilePath = Files.createTempFile("tmp-errors", ".log");
// Create a ProcessBuilder and redirect the error stream to the temporary file
ProcessBuilder pb = new ProcessBuilder("my-command")
.redirectError(Redirect.appendTo(tmpFilePath.toFile()));
// Start the process
Process process = pb.start();
// log the erros into this thread
Files.readAllLines(tmpFilePath,StandardCharsets.ISO_8859_1).forEach(LOGGER::error);
// Delete the temporary file after the process completes
Files.delete(tmpFilePath);
} catch (IOException | InterruptedException e) {
// Handle the exception
e.printStackTrace();
}
I want to execute an external process using Process Builder, collect the errors coming from the external process using redirectError() method, collect these errors from the temporary file and log them in the current thread and finaly delete the temporary file.
But I keep getting this error:
The process cannot access the file because it is being used by another process
I think the file is still locked by the Process Builder, but I couldn't find how to release it!