使用 Java Runtime.exec 通过 Ubuntu 中的终端触发命令 [英] firing a command through terminal in Ubuntu using Java Runtime.exec

查看:23
本文介绍了使用 Java Runtime.exec 通过 Ubuntu 中的终端触发命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这在 Windows 中相当简单,但在 Linux 中有点棘手.我正在使用

This is fairly simple in Windows, but a little tricky in Linux. I am using

Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "java -classpath /home/4/byz/Orc" });

其中 Orc 是带有 main 函数的类文件.但什么也没有发生.有什么设置吗?难道我做错了什么 ?

where Orc is the class file with a main function. But nothing happens. Are there any settings ? Am I doing something wrong ?

我希望java程序在终端运行.

I wish the java program to run in the terminal.

解决办法如下:

        String[] cmdArray = {"gnome-terminal","java -classpath /home/r/byz/ Orchestrator"};

        try {
            Runtime.getRuntime().exec(cmdArray);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

所以基本上,我们必须使用 gnome-terminal ..

So basically, we have to use gnome-terminal ..

推荐答案

我相信这已经解决了,但是我会发布一个答案:

I believe this is already resolved, however I'll post an answer:

如何运行:

executeCommand(new String[]{"/bin/bash", "-c", "java -classpath /home/4/byz/Orc"});

方法:

public String executeCommand(String[] cmd) {
    StringBuffer theRun = null;
    try {
        Process process = Runtime.getRuntime().exec(cmd);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
        int read;
        char[] buffer = new char[4096];
        StringBuffer output = new StringBuffer();
        while ((read = reader.read(buffer)) > 0) {
            theRun = output.append(buffer, 0, read);
        }
        reader.close();
        process.waitFor();

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
        return theRun.toString().trim();
}

让我知道这是否有帮助!

Let me know if this helps!

这篇关于使用 Java Runtime.exec 通过 Ubuntu 中的终端触发命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆