Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active September 23, 2017 17:30
Show Gist options
  • Save rponte/4493437 to your computer and use it in GitHub Desktop.
Save rponte/4493437 to your computer and use it in GitHub Desktop.
Executing Windows exe file with Java using ProcessBuilder.
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class WindowsExeFile {
private final File file;
public WindowsExeFile(String rawPath) {
this.file = convertToFile(rawPath);
}
public String getName() {
return file.getName();
}
public File getDirectory() {
return file.getParentFile();
}
public String getAbsolutePath() {
return file.getAbsolutePath();
}
@Override
public String toString() {
return getAbsolutePath();
}
private File convertToFile(String rawPath) {
try {
String decodedPath = URLDecoder.decode(rawPath, "utf-8");
return new File(decodedPath);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Não foi possível decodificar o caminho do executável, " + rawPath, e);
}
}
}
import java.util.Scanner;
public class WindowsExeRunner {
/**
* Executa o arquivo do Windows <code>exeFile</code> sem passar argumentos e
* retorna o output de sucesso.
*/
public String execute(WindowsExeFile exeFile) {
Scanner scanner = null;
try {
Process process = new ProcessBuilder(exeFile.getAbsolutePath())
.directory(exeFile.getDirectory()) // usa diretório do executável como working directory
.start();
process.waitFor();
scanner = new Scanner(process.getInputStream());
String output = scanner.useDelimiter("\\A").next();
return output;
} catch (Exception e) {
throw new IllegalStateException("Não foi possível executar o '" + exeFile + "': " + e.getMessage(), e);
} finally {
if (scanner != null) {
scanner.close();
}
}
}
}
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class WindowsExeRunnerTest {
private static final String WINDOWS_EXE = WindowsExeRunnerTest.class.getResource("Executavel_Windows_de_Teste.exe").getFile();
WindowsExeRunner windowsExeRunner;
@Before
public void setup() {
windowsExeRunner = new WindowsExeRunner();
}
@Test
public void deveriaExecutarWindowsExe_E_RetornarOutputDeSucesso() {
WindowsExeFile exeFile = new WindowsExeFile(WINDOWS_EXE);
String output = windowsExeRunner.execute(exeFile);
assertEquals("output do executavel", "Teste", output.trim());
}
@Test(expected=IllegalStateException.class)
public void deveriaRetornarErroQuandoNaoEncontrarArquivoExecutavel() {
WindowsExeFile invalidExeFile = new WindowsExeFile("invalid_exe_file.exe");
windowsExeRunner.execute(invalidExeFile);
}
}