Как сохранить результат команды cmd в переменную?
Пример:
Команда в консоли javac -version Результат: javac 1.8.0_251
Как сохранить результат javac 1.8.0_251 в переменную, к примеру (String ver).
Через гугл нашёл несколько примеров, но все они не сработали. Вот один из них:
public void Ver() throws IOException {
Process proc = Runtime.getRuntime().exec("cmd javac -version");
InputStream in = proc.getInputStream();
ArrayList ar = new ArrayList();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
br.readLine();
String l;
while ((l=br.readLine())!=null) {
ar.add(l);
}
System.out.println(l);
}
При выполнении просто зависает и всё.
Ответы (2 шт):
Автор решения: Andrew
→ Ссылка
Вот есть интересные способы:
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(
new InputStreamReader(proc.getErrorStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
Автор решения: Podushkoved
→ Ссылка
Чуть-чуть допилил ваш код. Всё нормально работает. Версия под linux:
Process proc = Runtime.getRuntime().exec("javac --version");
InputStream in = proc.getInputStream();
ArrayList<String> arr = new ArrayList<>();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
arr.add(line);
}
System.out.println(arr); // [javac 14]