ex_exec.java

来自「JAVA分布式程序学习的课件(全英文)」· Java 代码 · 共 46 行

JAVA
46
字号
// program to illustrate invoking a Unix shell to run a unix command 
//   from within a Java program

   import java.io.*;

class Ex_exec
{
	static PrintWriter screen = new PrintWriter(System.out, true);

	public static void main(String[] args) throws IOException
	{
           String s;
           String [ ] cmdarray;
           int number;
           cmdarray = new String[2];
           cmdarray[0] = "ls";
           cmdarray[1] = "-l";
           Process proc = Runtime.getRuntime().exec(cmdarray);
           /* If the subprocess takes input, this is how to write to it

           PrintWriter writeToShell
             = new PrintWriter (proc.getOutputStream());

           writeToShell.println("(load \"EBOOKS\")");
           */

           BufferedReader inputfromShell =
             new BufferedReader(new InputStreamReader
             (proc.getInputStream()));
           s = inputfromShell.readLine();
           while (s != null) {
              System.out.println(s);
              s = inputfromShell.readLine();
           }

           BufferedReader errorfromShell =
             new BufferedReader(new InputStreamReader
             (proc.getErrorStream()));
           s = errorfromShell.readLine();
           while (s != null) {
              System.out.println(s);
              s = errorfromShell.readLine();
           }
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?