如何使用BufferedReader从命令行输出中获取带有特殊字符的字符串

时间:2018-06-20 16:11:48

标签: java utf-8 bufferedreader

我有一个可以从命令行获取输出的类:

public final class StreamPumper implements Runnable {
  // input param is process.getInputStream()
  private BufferedReader reader = new LineNumberReader(new InputStreamReader(input, encoding)));
  @Override
  public void run() {
    try {
      String str = reader.readLine();
      while (str != null) {
        consumeLine(str);
        str = reader.readLine();
      }
    } catch (Exception e) {
      //
    } finally {
      IOUtils.closeQuietly(reader);
    }
  }
}

reader.readLine()将返回[32m √ [39m [90mResponse status: 200 - Login[39m,但我希望是√ Has 'error' in response body - error: unauthorized

另一个例子:[90m│[39m [90m│[39m executed [90m│[39m failed [90m│[39m

,我希望是│ │ executed │ failed │

如何使用此类从命令行输出中获取带有特殊字符的字符串? 它在命令行屏幕(Eclispe,IntelliJ,shell)上运行良好,但是在使用调试或保存到文件时会出现问题。 enter image description here

1 个答案:

答案 0 :(得分:1)

您只需设置与所需特殊字符相对应的编码即可。

以下内容适用于UTF-8

中包含的特殊字符
InputStreamReader isr = new InputStreamReader(System.in,"UTF-8");
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
System.out.println(str);

由于您使用的是LineNumberReader,它扩展了BufferedReader,因此以下代码可以很好地用于上述特殊符号:

InputStreamReader isr = new InputStreamReader(System.in,"UTF-8");
        LineNumberReader br = new LineNumberReader(isr);
        //BufferedReader br = new BufferedReader(isr);
        String str = br.readLine();
        System.out.println(str);

enter image description here

找到以下图片: