使用Java的流程构建器来调用C程序

时间:2015-04-13 15:56:39

标签: java c

尝试使用Java的流程构建器调用C程序,但不知道在流程构建器调用中调用什么。

Process p = new ProcessBuilder("myCommand", "myArg").start();

对于myCommandmyArg,我会用什么值替换它来运行C程序?我希望它调用的程序如下所示:

calculator.c:

#include <stdio.h>

int main ()
{
  int a = 4;
  int b = 2;
  int c = a + b;
  printf("Result: %d \n", c);
}

3 个答案:

答案 0 :(得分:4)

如果还没有编译calculator.c,你需要先编译它:

Process compile = new ProcessBuilder("gcc", "calculator.c").start();
Process execute = new ProcessBuilder("./a.out").start();

任何相关的编译器标志(例如-O-o calculator)也应包含在参数中。如果您确实重命名了可执行文件,那么您将要更改./a.out

更好的方法(就少数硬编码常数而言)将有一些变量,如:

String c_file = "calculator.c";
String output_exe = "calculator";
Process compile = new ProcessBuilder("gcc", "-o " + output_exe,  c_file).start();
Process execute = new ProcessBuilder("./" + output_exe);

最后,您可能希望确保每个进程都正在退出而不会出错:

if (compile.getInputStream().read() == -1) {
    // that means something was written to stderr, and you can do something like
    System.out.error("ERROR!");
    System.exit(-1);
}

正如@VinayDandekar指出的那样,您也可以使用exitValue执行此操作。

if (compile.exitValue() == -1) {
    // that means something was written to stderr, and you can do something like
    System.out.error("ERROR!");
    System.exit(-1);
}

答案 1 :(得分:2)

首先在Windows系统属性上设置环境变量的编译器路径否则它将无法工作。然后设置编译并运行代码

编译代码:`

     JFileChooser fileChooser=new JFileChooser();
    if (fileChooser.showSaveDialog(compile.this) != JFileChooser.APPROVE_OPTION)
                return;
            File file = fileChooser.getSelectedFile();
            try {
                FileWriter out = new FileWriter(file);
                textEditor.write(out);
                out.close();

            } catch (IOException e1) {
                e1.printStackTrace();
            }

            String filepath = file.getPath();
            String filepath2 = filepath.substring(0, filepath.lastIndexOf(File.separator));
            System.out.println(filepath);
            System.out.println(filepath2);
            String name = file.getName();


            String name2 = file.getName().substring(0, file.getName().lastIndexOf("."));
             String folder = filepath2+"\\";
        String exe = folder+name2+".exe";
             System.out.println(exe);

            ProcessBuilder pb=new ProcessBuilder();
              try {

                  pb = new ProcessBuilder("cmd", "/C", "gcc " + "\"" + filepath2 + "\\" + name + "\"" + " -o \"" + name2+"\"");


                  pb = new ProcessBuilder("cmd", "/C", "g++ " + "\"" + filepath2 + "\\" + name + "\"" + " -o \"" + name2+"\"");


                pb.directory(new File(filepath2));
                Process p = pb.start();
                p.waitFor();
                int x = p.exitValue();

                if (x == 0) {

                    area.setForeground(red);
                    area.setText("            == 0 error.. Compilation Finished");
                } else {

                    BufferedReader r = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                    //BufferedWriter rm=new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));


                    String out;
                    area.setText("");


                    while ((out = r.readLine()) != null)


                    {


                        area.setForeground(RED);
                        area.append(out + System.getProperty("line.separator"));
                    }


                }


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

`

运行代码:`

     JFileChooser fileChooser=new JFileChooser();
    if (fileChooser.showSaveDialog(compile.this) != JFileChooser.APPROVE_OPTION)
                return;
            File file = fileChooser.getSelectedFile();
            try {
                FileWriter out = new FileWriter(file);
                textEditor.write(out);
                out.close();

            } catch (IOException e1) {
                e1.printStackTrace();
            }
            String filepath = file.getPath();
            String filepath2 = filepath.substring(0, filepath.lastIndexOf(File.separator));
            System.out.println(filepath);
            System.out.println(filepath2);
            String name = file.getName();


            String name2 = file.getName().substring(0, file.getName().lastIndexOf("."));
             String folder = filepath2+"\\";
        String exe = folder+name2+".exe";
             System.out.println(exe);

            ProcessBuilder pb=new ProcessBuilder();
              try {

                  pb = new ProcessBuilder("cmd", "/C", "gcc " + "\"" + filepath2 + "\\" + name + "\"" + " -o \"" + name2+"\"");


                  pb = new ProcessBuilder("cmd", "/C", "g++ " + "\"" + filepath2 + "\\" + name + "\"" + " -o \"" + name2+"\"");


                pb.directory(new File(filepath2));
                Process p = pb.start();
                p.waitFor();
                int x = p.exitValue();
                int z=p.exitValue();

                if (x == 0) {

                    Runtime rt = Runtime.getRuntime();
                    try {
                        String username = System.getProperty("user.name");
                        String c = "@echo off\n" + "\"" +
                                filepath2 + "\\" + name2 + ".exe\"\n" + "echo.\n" + "echo.\n" + "echo Process Terminated\n" +
                                "pause\n" +
                                "exit";


                        File dir = new File("C:\\Users\\" + username + "\\CodeEditor");
                        dir.mkdir();

                        try {
                            File file2 = new File("C:\\Users\\" + username + "\\CodeEditor" + "\\run.bat");
                            file2.createNewFile();
                            PrintWriter writer = new PrintWriter(file2);
                            writer.println(c);
                            writer.close();


                            Process p2 = Runtime.getRuntime().exec("cmd /c start run.bat", null, new File("C:\\Users\\" + username + "\\CodeEditor"));
                        } catch (Exception ex) {

                        }


                    } catch (Exception ex) {

                    }

                } else {


                    JOptionPane.showMessageDialog(compile.this, "Compilation Error", "Error", JOptionPane.ERROR_MESSAGE);

                }


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

`

完成!!!

答案 2 :(得分:0)

运行时可用于执行OS支持的任何命令行指令。

以下示例将有所帮助。

package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CommandExec {

public static void main(String[] args) {
    try {
        Process pr = Runtime.getRuntime().exec("ls /etc");
        BufferedReader read = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String str = read.readLine();
        while (str != null){
            System.out.println(str);
            str = read.readLine();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}