0

我有这个代码

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

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

4

3 回答 3

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);
于 2013-09-28T05:16:54.370 回答
0

尝试

 String line = in.readLine();
 if(line!=null && line.length() >5)
     line = line.substring(0, 5);
于 2013-09-28T04:57:19.660 回答
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

于 2013-09-28T04:57:30.217 回答