提取字符串

时间:2015-05-01 05:52:41

标签: java adb

我正在尝试使用“adb devices”命令为Android提取设备名称.. 通过使用这种方法,我得到了:

public void newExec() throws IOException, InterruptedException, BadLocationException{
    String adbPath = "/Volumes/development/android-sdk-macosx/tools/adb";
    String cmd = adbPath+" "+"devices";

    Process p;
    p = Runtime.getRuntime().exec(cmd);
    p.waitFor();

    String line;

    BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    while ((line = err.readLine()) != null) {
        System.out.println(line);
    }
    err.close();

    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line=input.readLine()) != null) {
        //printing in the console 
        System.out.println(line);
    }
    input.close();
}

输出结果为:

  

所附设备清单
  192.168.56.101:5555设备

我试图从这个输出中只获取设备名称:

  

192.168.56.101:5555

我在很多方面使用过分裂,例如:

String devices = "List of devices attached";
System.out.println(line.split(devices);

但这根本不起作用!

我不想要一种静态方式,而是一种动态方式。我的意思是,如果设备名称已更改或存在多个列出的设备,我想要一种方法只提供设备名称。 有没有办法呢?

很抱歉,如果问题不是那么清楚,我对Java不是新手:)

4 个答案:

答案 0 :(得分:3)

您可以尝试以下代码:

adb devices的下一行输出由制表符分隔,因此我们必须使用" \ t"作为论点。

List<String> deviceList = new ArrayList<String>();

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
    if (line.endsWith("device")) {
        deviceList.add(line.split("\\t")[0]);
    }

}

for (String device : deviceList) {
    System.out.println(device);
}

答案 1 :(得分:1)

使用以下代码(注意:它仅在每次输出字符串相同时才有效)

parameters: 
    # Overriding Security Bundle's Access Listener class to provide  detailed
    # error message
services:
    acme_api.question_manager:
        class: AcmeApiBundle\Manager\QuestionManager
        arguments:
          - @doctrine
          - @validator

输出:

  

192.168.56.101:5555

希望这会对你有所帮助。

答案 2 :(得分:0)

我对Android编程并不熟悉,但对我而言,这听起来像是一个简单的字符串解析问题,而不是特定于android。无论如何,我在这里2美分。只有当它以

结尾时才可以尝试解析这些行
        String line;
        List<String> devices = new ArrayList<String>();
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line=input.readLine())!=null){
            //printing in the console 
            System.out.println(line);
            if (!line.endsWith("device")) {
                //skip if it does not ends with suffix 'device'
                continue;
            }
            else {
                //parse it now
                String[] str = line.split(" ");
                devices.add(str[0]);
            }

        }

答案 3 :(得分:0)

似乎您使用的String split()方法错误。

  String devices = "List of devices attached";

    System.out.println(line.split(devices);

使用示例:

        String[] ss = "This is a test".split("a");

    for (String s: ss )
        System.out.println(s);

输出

  

这是

     

测试

split(String regex)的参数必须是正则表达式(正则表达式)。 此外,您可以使用StringTokenizer类或Scanner类。这些类有更多的标记化选项。