1肴沫、將c語言代碼寫入.c文件
try {
BufferedWriter out = new BufferedWriter(new FileWriter("demo.c"));
out.write("#include<stdio.h>\n" +
"int main(){\n" +
"\tprintf(\"hello linux\\n\");\n" +
"\treturn 0;\n" +
"}");
out.close();
System.out.println("demo.c創(chuàng)建成功!");
} catch (IOException e) {
}
2蕴忆、調(diào)用shell文件運行
Process process;
try {
process = Runtime.getRuntime().exec("bash ./chkRun.shell");//運行我的shell腳本
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
int exitValue = process.waitFor();
while((line = reader.readLine())!= null){
System.out.println(line);
}
if (exitValue == 0){
System.out.println( "successfully executed the linux command");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
3颤芬、java代碼整合
TestShell.java
import java.io.*;
public class TestShell {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("demo.c"));
out.write("#include<stdio.h>\n" +
"int main(){\n" +
"\tprintf(\"hello linux\\n\");\n" +
"\treturn 0;\n" +
"}");
out.close();
System.out.println("demo.c創(chuàng)建成功!");
} catch (IOException e) {
}
Process process;
try {
process = Runtime.getRuntime().exec("bash ./chkRun.shell");//運行我的shell腳本
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
int exitValue = process.waitFor();
while((line = reader.readLine())!= null){
System.out.println(line);
}
if (exitValue == 0){
System.out.println( "successfully executed the linux command");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
4套鹅、linux系統(tǒng)中上傳java文件站蝠,并且編寫shell腳本
touch chkRun.shell
vim chkRun.shell
`
`
`
`
gcc demo.c -o demo.out
./demo.out
rm demo.out
rm demo.c
image.png
此時目錄下應(yīng)該只有一個shell文件和一個java文件
5、自動化編譯java使其編譯c
javac TestShell.java
java TestShell
image.png
看見c編譯后運行結(jié)果出現(xiàn)