1

Пример:

Команда в консоли 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 ответа 2

2

Чуть-чуть допилил ваш код. Всё нормально работает. Версия под 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]
1
  • Я так и подумал! И в примере написал javac --version, так как все знают что это! А, оказалось не все так просто!!! С cmd я тоже пробовал! Всё просто виснет!
    – EugeneTM
    2 мая 2020 в 9:15
2

Вот есть интересные способы:

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);
}
0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.