2013-09-28 91 views
0

我有这样的代码如何从缓冲读取器读取前五个字符?

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

从终端运行它的第一线oupout返回Busybox的版本。如果我想像我那样举例说前5个角色?

+0

你想读缓冲读写器的前五个字符吗? –

+0

是.............. –

+0

@ MariocciRossini - 只需使用subString(int startposition,int endposition)...我认为这会对你有帮助。 – FarhaSameer786

回答

0

尝试

String line = in.readLine(); 
if(line!=null && line.length() >5) 
    line = line.substring(0, 5); 
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

+0

应该是buffer.toString()。substring(0,5)? – upog

2

而其他的答案应该工作也很好,以下将在完成之后退出并关闭流ding 5个字符:

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