繁体   English   中英

从jar运行shell命令?

[英]Run shell command from jar?

从Java调用shell命令的通常方法是这样的:

Process process = Runtime.getRuntime().exec(command);

并且正常工作。 但是现在我已经将项目导出到可执行的jar文件中,并且callig shell命令不再起作用。 是否有此问题的解释,解决方案或解决方法?

菲尼亚斯

-

编辑:

  • 即使键盘中断(ctrl + c; ctrl + d)也无法识别。

  • 杀死Java后终端输入不起作用

-

最小程序:

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;

public class Test {
    public static String fileName = "";

    /** test if you can open a 7z archive file with a given password */
    public static boolean test(String password)
        throws IOException, InterruptedException {
        String command = "7z l "+fileName;

        Process process = Runtime.getRuntime().exec(command);

        OutputStream out = process.getOutputStream();
        OutputStreamWriter w = new OutputStreamWriter(out);
        BufferedWriter writer = new BufferedWriter(w);
        writer.write(password+"\n");
        writer.close();
        w.close();
        out.close();

        if(process.waitFor() == 0) {
            return true;
        }
        else {
            return false;
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        fileName = args[0];
        test(args[1]);
    }
}

如果运行测试程序并使用ps或任务管理器,则会注意到7z正在运行。 您的问题是您没有使用流程的输出。 因此7z很快就被阻止尝试输出存档内容。

如果您在process.waitFor()之前添加以下行,则将获得一个正常运行的程序:

    InputStream in = process.getInputStream();
    byte[] buf = new byte[256];
    while (true) {
        int c = in.read(buf);
        if (c == -1)
            break;
        System.out.println(new String(buf));
    }

但是,这只会消耗您需要使用process.getErrorStream()进行相同处理的标准输出。 您可能会发现使用ProcessBuilder来启动进程更容易,因为它允许您合并stderr和stdout流。

您应该阅读这篇关于在Java中运行外部进程的陷阱的出色的JavaWorld文章

我猜您的问题出在执行命令的基本路径上。 有一种方法可以在调用exec时显式设置它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM