小弟初学Java求教Java如何执行外部程序,如象exec或CreatProcess()之类的函数,要是在Linux下如何做呢?

解决方案 »

  1.   

    应该差不多吧
    只要你熟悉linux的命令
      

  2.   

    呵呵,Win下用Java实现偶也不知道啊。
      

  3.   

    try{
    String[] command=new String[]{"D:\\Office\\Microsoft Office\\Office10\\WINWORD.EXE","E:\\tt.doc"};
    Process prop=Runtime.getRuntime().exec(command);

    }catch(Exception ex)
    {
    ex.printStackTrace();
    }
      

  4.   

    给你一个jdk5.0下的例子:
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;public class ProcessBuilderDemo {
    public static void main(String[] args) {
    //Physical Address. . . . . . . . . :
    InputStream input = null;
    try{
    //执行命令
    ProcessBuilder builder = new ProcessBuilder("ipconfig" ,"/all");
    Process process = builder.start();
    input = process.getInputStream();

    //把得到的流得到
    byte[] b = new byte[1024];
    StringBuffer buffer = new StringBuffer();
    while (input.read(b) > 0) {
    buffer.append(new String(b));
    }

    //分析流
    String value = buffer.substring(0);
    String systemFlag = "Physical Address. . . . . . . . . :";
    int index = value.indexOf(systemFlag);
    List<String> address = new ArrayList<String>();
    if (0 < index) {
    value = buffer.substring(index + systemFlag.length());
    address.add(value.substring(0, 18));
    } //打印输出
    for (String add : address) {
    System.out.println(add);
    }
    } catch (Exception ex) {
    ex.printStackTrace();
    } finally {
    try {
    input.close();
    }
    catch (IOException ex) {
    ex.printStackTrace();
    }
    }
    }
    }
      

  5.   

    jdk1.4下没有ProcessBuilder类 不过可以通过Runtime的exec方法执行 基本原理一样 呵呵
      

  6.   

    这个例子是获得本机的MAC地址
      

  7.   

    恩,win下的我试过了,谢谢norikos(zhulgxg)啊 。可是Linux下是不是一样呢?不如要执行RedHat自带的计算器如何实现啊。
      

  8.   

    在Linux下,或者是有个pro1的程序,我试Process prop=Runtime.getRuntime().exec("pro1");
    是不能运行的。求助啊。
      

  9.   

    linux:
    try {
        String command = "/bin/echo";
        command += " 'FirstLine\nSecond Line'";
        command +=" | /usr/bin/mail";
        command +=" -a 'From: someone'";
        command +=" -s 'Subject'";
        command +=" [email protected]";
        //   /bin/sh是unix下的cmd
        Process send = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c",command });
    } catch (IOException e) {
        System.out.println(e.toString());
    }
    //FOR WINDOWS 95 AND 98 USE COMMAND.COM
    if(osName.equals("Windows 95") || osName.equals("Windows 98")){
        Runtime.getRuntime().exec("command.com /C start acrord32 /p /h" + claim.pdf);
    }
    //FOR WINDOWS NT/XP/2000 USE CMD.EXE
    else {
        Runtime.getRuntime().exec("cmd.exe start /C acrord32 /p /h" + claim.pdf);
    }