Java执行linux命令 获取执行结果

package test;

//java使用Runtime.exec执行linux命令 获取执行结果
//java -cp /home/ymiao/linux_java_project/classes test.ExecTest
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ExecTest
{
    public static void main(String[] args)
    {
        System.out.println("test!");

        String[] cmd = { "sh", "-c", "ls > FILE" };
        try
        {
            Process ps = Runtime.getRuntime().exec(cmd);
            System.out.print(loadStream(ps.getInputStream()));
            System.err.print(loadStream(ps.getErrorStream()));
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
            System.out.println("IOException");
        }
    }

    // read an input-stream into a String
    static String loadStream(InputStream in) throws IOException
    {
        int ptr = 0;
        in = new BufferedInputStream(in);
        StringBuffer buffer = new StringBuffer();
        while ((ptr = in.read()) != -1)
        {
            buffer.append((char) ptr);
        }
        return buffer.toString();

    }

}

你可能感兴趣的:(4_Java)