在java中保持换行符和回车符(groovy)
我试图从Linux框中获取命令输出
例如: tnsping
我想保留它的换行符。
下面是我向frows
添加命令并将其传递给函数执行的代码
def oracleCommand(csm,pluginOutputs) { HashMap params = IntermediateResults.get("userparams") Map env=AppContext.get(AppCtxProperties.environmentVariables) def fClass = new GroovyClassLoader().parseClass( new File( 'plugins/infa9/Infa9CommandExecUtil.groovy' ) ) List frows frows=["tnsping $params.tns"] //for the time being only one command is here List resultRows = fClass.newInstance().fetchCommandOutput( params, env, frows ) csm.oracleCommand(){ oracle_input(frows[0]){} oracle_output(resultRows[0]){} } }
在下面的代码中,我正在读取结果,根据换行分割结果,所以我的所有新行都消失了
public List fetchCommandOutput( Map params, Map env, List rows ) { List outputRows = new ArrayList() 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时遇到
它应保留其格式?
如果我找对你,你应该使用\r
和\n
:
result.append(line+"\r\n");
或者,您可以从系统中获取行分隔符:
result.append(line+System.getProperty("line.separator"));
如果你使你的function更Groovy:
public List fetchCommandOutput( Map params, Map env, List 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 } }
我相信它可以使输出保持与过程输出完全相同的格式…而且你需要维护的代码更少……