在java中保持换行符和回车符(groovy)

时间:2011-11-03 11:37:11

标签: java groovy

我正在尝试从Linux框中获取命令输出

例如:tnsping

我希望保留它的换行符。

下面是我将命令添加到frows并将其传递给执行函数的代码

def oracleCommand(csm,pluginOutputs)
{
HashMap<String,String> params = IntermediateResults.get("userparams")
Map env=AppContext.get(AppCtxProperties.environmentVariables)

def fClass = new GroovyClassLoader().parseClass( new File( 'plugins/infa9/Infa9CommandExecUtil.groovy' ) )
List<String> frows
frows=["tnsping $params.tns"]  //for the time being only one command is here

List<String> resultRows = fClass.newInstance().fetchCommandOutput( params, env, frows )

csm.oracleCommand(){
    oracle_input(frows[0]){}
    oracle_output(resultRows[0]){}
}
}

在下面的代码中我正在阅读结果,根据换行分割结果,所以我的所有换行都消失了

    public List<String> fetchCommandOutput( Map<String,String> params, Map env, List<String> rows )
  {

        List<String> outputRows = new ArrayList<String>()
        try
        {
            for(item in rows)
            {
                String temp=item.toString()

                Process proc = Runtime.getRuntime().exec(temp);
                InputStream stdin = proc.getInputStream();
                InputStreamReader isr = new InputStreamReader(stdin);
                BufferedReader br = new BufferedReader(isr);
                String line = null;

                result = new StringBuffer()
                line=null


                while ((line = br.readLine()) != null)
                {
                    result.append(line+" #10#13 ")  //Here i am trying to add the newline again, but it does not reflect in the generated xml. it just come as plain text
                }
                String tRes=result
                tRes=tRes.trim()

                outputRows.add(tRes)
                int exitVal = proc.waitFor();

            }
        }
        catch (IOException io)
        {
            io.printStackTrace();
        }
        catch (InterruptedException ie)
        {
            ie.printStackTrace();
        }

    return  outputRows
  }

更新 如何保留我的换行符或回车符,以便在使用xsl打开xml时遇到<pre></pre>时它应该保留其格式?

2 个答案:

答案 0 :(得分:2)

如果我找到你,你应该使用\r\n

result.append(line+"\r\n");

或者,您可以从系统中获取行分隔符:

result.append(line+System.getProperty("line.separator"));

答案 1 :(得分:1)

如果你使你的功能更加Groovy:

  public List<String> fetchCommandOutput( Map<String,String> params, Map env, List<String> rows )
  {
    rows.collect { item ->
      def (outtxt, errtxt) = [new StringBuffer(), new StringBuffer()].with { inbuf, errbuf ->
        def proc = item.execute()
        proc.waitForProcessOutput( inbuf, errbuf )
        [ inbuf, errbuf ]*.toString()*.trim()
      }
      if( errtxt ) {
        println "Got error $errtxt running $item"
      }
      outtxt
    }
  }

我相信它可以使输出保持与过程输出完全相同的格式......而且您需要维护的代码更少......