我正在创建一个编辑器类型的应用程序,我想在其中编译和运行(当然也创建、编辑、打开)C、C++ 和 Java 文件; 我正在用 Java 创建它。
现在为了编译和运行,我正在获取文件的整个路径 并通过这个完整路径编译和运行。
例如。
compileFileCommand = javac /media/disk/eclipse/\/UniversalIDE/Java/FirstJava.java
try
{
System.out.println("Compiling Java File");
Process compileProcess = Runtime.getRuntime().exec(compileFileCommand);
compileProcess.waitFor();
String line = "";
BufferedReader bri = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream()));
while ((line = bri.readLine()) != null)
{
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null)
{
System.out.println(line);
}
bre.close();
compileProcess.waitFor();
System.out.println("Done Java Compile.");
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception in Java Compile. ");
System.out.println(e.getMessage());
}
上面的代码工作正常,并在 java 文件的位置创建一个类文件。但是 bri.readLine() 始终包含 null。
用于运行Java文件
runFileCommand = java /media/disk/eclipse/\/UniversalIDE/Java/FirstJava
对于运行 C 和 CPP 文件,过程相同
对于C编译
String compileFileCommand = "gcc " + fileNameWithFullPath;
对于 C 运行
String runFileCommand = "./" + fileNameWithFullPath.split(".c")[0];
用于CPP编译
String compileFileCommand = "g++ " + fileNameWithFullPath;
对于 CPP 运行
String runFileCommand = "./" + fileNameWithFullPath.split(".cpp")[0];
我使用与编译 java 文件相同的代码,但它没有给出任何结果,并且 bri.readLine() 始终给出 null。
请帮助我解决这个问题,并对我的应用程序提出任何建议。
最佳答案
gcc 和 g++ 的默认输出文件名是 a.out
,而不是没有扩展名的输入文件名。
尝试 runFileCommand = "./a.out"
,或使用 gcc/g++ 的 -o
选项来指定输出文件名。
此外,当没有错误或警告时,所有编译命令都不会输出任何内容。
关于java - 如何在C、java和C++中编译和运行任意位置的任意文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9190823/