【问题标题】:How do I read the last line in the console output?如何读取控制台输出的最后一行?
【发布时间】:2017-02-13 02:09:46
【问题描述】:

所以我试图制作一个使用 adb 和 fastboot 来根植我的 Nexus 6P 的 Java 程序。我有一个可以运行命令的类,但我需要从输出中捕获设备 ID。当我运行 adbfastboot 时,输出看起来像下面三个选项之一

List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
5VT7N16324000434          device

List of devices attached
5VT7N16324000434          device

5VT7N16324000434          device

现在我需要捕获5VT7N16324000434 并将其保存到字符串中。虽然它不会总是一样的。我已经搜索了几个小时没有任何帮助,甚至不知道从哪里开始。

我用这个类运行 adb

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecuteShellCommand {

public static void main(String inputCommand) {

    ExecuteShellCommand obj = new ExecuteShellCommand();

    String command = inputCommand;

    String output = obj.executeCommand(command);

    System.out.println(output);

}

private String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

}

}

然后我需要读取5VT7N16324000434 的输出或任何可能在该位置的字符串。

【问题讨论】:

  • 请展示你到目前为止所做的尝试
  • 我什么都没试过,因为我不知道从哪里开始
  • 你如何运行adb
  • 我更新了问题,因为我无法在此处粘贴我的代码并且链接不起作用@ScaryWombat
  • 我更新了问题 - 你应该这样做。现在你得到的输出是什么?

标签: java console output console-application


【解决方案1】:

我不确定,但我想到的唯一解决方案是路由 PrintStream (System.out) 并将打印的每一行分配给名为 lastLine 的字符串或其他东西。然后,您可以使用删除实际设备 ID 后的空格/制表符的正则表达式获取设备 ID
像这样 -> (DEVICEID device) 到 (DEVICEID) 或使用 String.replaceAll(" ", ""); 替换每个空格,使用 String.replace("device", ""); 替换“设备”字样。我希望我能帮助你,因为我是这个社区的新手。

编辑:
这是将最后一行分配给字符串的代码:


private String lastLine;

public void construct() {
    System.setOut(new PrintStream(System.out) {
        public void println(String s) {
            lastLine = s;
            super.println(s);
        }
    });
}

PS:对不起我的英语不好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    相关资源
    最近更新 更多