首页 > 基础资料 博客日记

java执行命令行命令,编译运行另一个java文件

2024-09-20 22:00:07基础资料围观5

Java资料网推荐java执行命令行命令,编译运行另一个java文件这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣

本文介绍在java项目中使用cmd命令行去编译并运行电脑上的java文件。

1.前置工作

创建maven项目,引入 hutool 工具包依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.8</version>
        </dependency>

 2.在项目目录下新建一个CodeRepo文件夹

存放 java 或者 class 文件

 

 3.编码

准备好一个字符串,可以写入变成 java 文件进行编译。

设置java文件的名字为Main.java。

设置存放java和class文件的文件夹名字。

    private static final String CODE = "public class Main {\n" +
            "    public static void main(String[] args) {\n" +
            "        System.out.println(\"结果 = \"+ 1 + 2);\n" +
            "    }\n" +
            "}\n";
    private static final String CODE_FILE_NAME = "Main.java";

    private static final String CODE_TEMP_PATH = "CodeRepo";

 获得当前项目在电脑上的绝对路径

String projectPath = System.getProperty("user.dir");

 把字符串内容写入Main.java ,并设置Main.java 的父目录为UUID 随机生成的字符串,防止再次运行生成同名文件报错。

//CodeRepo 的绝对路径
String codeTempPath = projectPath + File.separator + CODE_TEMP_PATH;
//生成的java文件的绝对路径
String codePath = codeTempPath + File.separator + UUID.randomUUID()
                + File.separator + CODE_FILE_NAME;
//创建文件并把字符串内容写入
File file = FileUtil.writeString(CODE, codePath, StandardCharsets.UTF_8);
//创建的文件的绝对路径
String fileAbsolutePath = file.getAbsolutePath();

 剩下的主要代码:

        String compileCommand = "javac -encoding utf-8 " + fileAbsolutePath;
        //String runCommand = "java -Xmx256m -Dfile.encoding=UTF-8 -cp " + file.getParentFile() + " Main";
        //-Xmx256m 指定虚拟机最大的内存
        String runCommand = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main", file.getParentFile());
        // 执行命令,
        try {
            //todo 编译
            Process process = Runtime.getRuntime().exec(compileCommand);
            String compileMessage = ProcessUtil.execute(process, "Compile");
            System.out.println(compileMessage);
            //todo 运行
            process = Runtime.getRuntime().exec(runCommand);
            String runMessage = ProcessUtil.execute(process, "Run");
            System.out.println(runMessage);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //运行完删除文件
        boolean del = FileUtil.del(file.getParentFile());
        if(del){
            System.out.println("删除成功!");
        }

4.运行 

总代码

public class Command {
    private static final String CODE = "public class Main {\n" +
            "    public static void main(String[] args) {\n" +
            "        System.out.println(\"结果 = \"+ 1 + 2);\n" +
            "    }\n" +
            "}\n";
    private static final String CODE_FILE_NAME = "Main.java";

    private static final String CODE_TEMP_PATH = "CodeRepo";

    public static void main(String[] args) {
        String projectPath = System.getProperty("user.dir");
        System.out.println("项目路径 = " + projectPath);
        String codeTempPath = projectPath + File.separator + CODE_TEMP_PATH;
        String codePath = codeTempPath + File.separator + UUID.randomUUID()
                + File.separator + CODE_FILE_NAME;
        File file = FileUtil.writeString(CODE, codePath, StandardCharsets.UTF_8);
        String fileAbsolutePath = file.getAbsolutePath();
        System.out.println(fileAbsolutePath);
        String compileCommand = "javac -encoding utf-8 " + fileAbsolutePath;
        //String runCommand = "java -Xmx256m -Dfile.encoding=UTF-8 -cp " + file.getParentFile() + " Main";
        //-Xmx256m 指定虚拟机最大的内存
        String runCommand = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main", file.getParentFile());
        // 执行命令,
        try {
            //todo 编译
            Process process = Runtime.getRuntime().exec(compileCommand);
            // 等待命令执行完成
            int exitVal = process.waitFor();
            System.out.println("Exit value: " + exitVal);
            if (exitVal == 0) {
                //运行成功
                InputStream inputStream = process.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String runMessage = bufferedReader.readLine();
                System.out.println("RunMessage = " + runMessage);
            }else{
                InputStream errorInputStream = process.getErrorStream();
                InputStreamReader inputStreamReader = new InputStreamReader(errorInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String errorMessage = bufferedReader.readLine();
                System.out.println("ErrorMessage = " + errorMessage);
            }
            //todo 运行
            process = Runtime.getRuntime().exec(runCommand);
            // 等待命令执行完成
            exitVal = process.waitFor();
            System.out.println("Exit value: " + exitVal);
            if (exitVal == 0) {
                //运行成功
                InputStream inputStream = process.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String runMessage = bufferedReader.readLine();
                System.out.println("RunMessage = " + runMessage);
            }else{
                InputStream errorInputStream = process.getErrorStream();
                InputStreamReader inputStreamReader = new InputStreamReader(errorInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String errorMessage = bufferedReader.readLine();
                System.out.println("ErrorMessage = " + errorMessage);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //运行完删除文件
        boolean del = FileUtil.del(file.getParentFile());
        if(del){
            System.out.println("删除成功!");
        }

    }
}

5.额外

在进一步,提取出一个编译运行的工具类

代码如下:

public class ProcessUtil {
    public static String execute(Process process, String Operate) {
        try {
            // 等待命令执行完成,返回状态码
            int exitVal = process.waitFor();
            System.out.println(Operate + " Exit value: " + exitVal);
            if (exitVal == 0) {
                //成功
                System.out.println(Operate + "成功!");
                InputStream inputStream = process.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String Message = bufferedReader.readLine();
                System.out.println("Message = " + Message);
                return "success, reason = " + Message;
            } else {
                //失败
                System.out.println(Operate + "失败!");
                InputStream errorInputStream = process.getErrorStream();
                InputStreamReader inputStreamReader = new InputStreamReader(errorInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String errorMessage = bufferedReader.readLine();
                System.out.println("ErrorMessage = " + errorMessage);
                return "false, reason = " + errorMessage;
            }
        } catch (Exception e) {
            return "false";
        }
    }
}

 

Command.java文件代码如下:

public class Command {
    private static final String CODE = "public class Main {\n" +
            "    public static void main(String[] args) {\n" +
            "        System.out.println(\"结果 = \"+ 1 + 2);\n" +
            "    }\n" +
            "}\n";
    private static final String CODE_FILE_NAME = "Main.java";

    private static final String CODE_TEMP_PATH = "CodeRepo";

    public static void main(String[] args) {
        String projectPath = System.getProperty("user.dir");
        System.out.println("项目路径 = " + projectPath);
        String codeTempPath = projectPath + File.separator + CODE_TEMP_PATH;
        String codePath = codeTempPath + File.separator + UUID.randomUUID()
                + File.separator + CODE_FILE_NAME;
        File file = FileUtil.writeString(CODE, codePath, StandardCharsets.UTF_8);
        String fileAbsolutePath = file.getAbsolutePath();
        System.out.println(fileAbsolutePath);
        String compileCommand = "javac -encoding utf-8 " + fileAbsolutePath;
        //String runCommand = "java -Xmx256m -Dfile.encoding=UTF-8 -cp " + file.getParentFile() + " Main";
        //-Xmx256m 指定虚拟机最大的内存
        String runCommand = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main", file.getParentFile());
        // 执行命令,
        try {
            //todo 编译
            Process process = Runtime.getRuntime().exec(compileCommand);
            String compileMessage = ProcessUtil.execute(process, "Compile");
            System.out.println(compileMessage);
            //todo 运行
            process = Runtime.getRuntime().exec(runCommand);
            String runMessage = ProcessUtil.execute(process, "Run");
            System.out.println(runMessage);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //运行完删除文件
        boolean del = FileUtil.del(file.getParentFile());
        if(del){
            System.out.println("删除成功!");
        }

        // 获取命令执行结果的输入流
        //BufferedReader reader = new BufferedReader
        //                          (new InputStreamReader(process.getInputStream()));

    }
}

执行

 

 


文章来源:https://blog.csdn.net/m0_73512487/article/details/140219899
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云