Runtime.getRuntime()

    技术2022-05-19  19

    权声明:转载时请以超链接形式标明文章原始出处和作者信息及 本声明 http://1504745673.blogbus.com/logs/77395808.html 假如要在java程序里执行一条linux可以用下面的写法Java代码 Processprocess=Runtime.getRuntime().exec(cmd); process.waitFor(); Processprocess=Runtime.getRuntime().exec(cmd);process.waitFor(); 但是当碰到像cd这样的命令时,上面的这种写法切不管用,很多时候我们以为是命令输错了或是文件找不到。 现在提供一种新的执行命令方法:Java代码 Filewd=newFile("/bin"); System.out.println(wd); Processproc=null; try{ proc=runtime.getruntime().exec("/bin/bash",null,wd); } catch(IOException e){ e.printStackTrace(); } if(proc!=null){ BufferedReaderin=newBufferedReader(newInputStreamReader(proc.getInputStream())); PrintWriterout=newPrintWriter(newBufferedWriter(newOutputStreamWriter(proc.getOutputStream())),true); out.println("cd.."); out.println("pwd"); out.println("exit"); try{ Stringline; while((line=in.readLine())!=null){ System.out.println(line); } proc.waitFor(); in.close(); out.close(); proc.destroy(); } catch(Exception e){ e.printStackTrace(); }} Filewd=newFile("/bin");System.out.println(wd);Processproc=null;try{proc=runtime.getruntime().exec("/bin/bash",null,wd);}catch(IOException e){e.printStackTrace();}if(proc!=null){BufferedReaderin=newBufferedReader(newInputStreamReader(proc.getInputStream()));PrintWriterout=newPrintWriter(newBufferedWriter(newOutputStreamWriter(proc.getOutputStream())),true);out.println("cd..");out.println("pwd");out.println("exit");try{Stringline;while((line=in.readLine())!=null){System.out.println(line);}proc.waitFor();in.close();out.close();proc.destroy();}catch(Exception e){e.printStackTrace();}}

    最新回复(0)