如何从缓冲读卡器中读取前五个字符?

时间:2013-09-28 04:50:35

标签: java android xml root busybox

我有这段代码

Process p =Runtime.getRuntime().exec("busybox");
        InputStream a = p.getInputStream();
        InputStreamReader read = new InputStreamReader(a);
        BufferedReader in = new BufferedReader(read);

从终端运行它,oupout的第一行返回Busybox的版本。如果我想像我一样拿前5个字符?

3 个答案:

答案 0 :(得分:2)

虽然其他答案也应该运行良好,但在阅读了五个字符后,以下内容将退出并关闭流:

    Process p = Runtime.getRuntime().exec("busybox");
    InputStream a = p.getInputStream();
    InputStreamReader read = new InputStreamReader(a);

    StringBuilder firstFiveChars = new StringBuilder();

    int ch = read.read();

    while (ch != -1 && firstFiveChars.length() < 5) {
        firstFiveChars.append((char)ch);
        ch = read.read();
    }

    read.close();
    a.close();

    System.out.println(firstFiveChars);

答案 1 :(得分:0)

尝试

 String line = in.readLine();
 if(line!=null && line.length() >5)
     line = line.substring(0, 5);

答案 2 :(得分:0)

这样做

Process p;
        try {
            p = Runtime.getRuntime().exec("busybox");
            InputStream a = p.getInputStream();
            InputStreamReader read = new InputStreamReader(a);
            BufferedReader in = new BufferedReader(read);
            StringBuilder buffer = new StringBuilder();
            String line = null;
            try {
                while ((line = in.readLine()) != null) {
                    buffer.append(line);
                }

            } finally {
                read.close();
                in.close();
            }

            String result = buffer.toString().substring(0, 15);
            System.out.println("Result : " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }

<强>输出

结果:BusyBox v1.13.3