从java运行Bash不起作用

时间:2014-09-12 19:38:51

标签: java linux bash centos

我有这个bash:

#!/bin/bash
# File to be tagged
inputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/Text.txt"
#inputfile="test/SampleInputs/longParagraph.txt"
# Tagged file to be created
#outputfile="test/SampleOutputs/NERTest.conll.tagged.txt"
outputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/1.Generate-Basic-Questions/Tagged-Named-Entites-Text.txt"
# Config file
#configfile="config/conll.config"
configfile="config/ontonotes.config"
# Classpath
cpath="target/classes:target/dependency/*"
CMD="java -classpath  ${cpath} -Xmx8g edu.illinois.cs.cogcomp.LbjNer.LbjTagger.NerTagger -annotate ${inputfile} ${outputfile} ${configfile}"
echo "$0: running command '$CMD'..."
$CMD

当我在下面运行java代码时,它们不会给出任何错误,但它们只是在我的Eclipse控制台中显示bash文件,换句话说它们不会运行bash! process.exitValue()的值是1,顺便说一句,我的操作系统是CentOS,linux。

Firs JAVA代码:

try {
     Process process = new ProcessBuilder(command).start();
     process.waitFor();
     System.out.println(process.exitValue());
        BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        while ((line = buf.readLine()) != null) {
            System.out.println("exec response: " + line);
        }
    } catch (Exception e) {
        System.out.println(e);
    }

第二个JAVA代码:

    String command = "/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/"
            + "SinaGolestanirad-Project/1.Generate-Basic-Questions/1.IllinoisNerExtended-DO-NOT-OPEN-BY-ECLIPSE/plaintextannotate-linux.sh";
     StringBuffer output = new StringBuffer();

    Process p;
    try {
        String[] cmd = new String[]{"/bin/bash",command};
        p = Runtime.getRuntime().exec(cmd);

        p.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                p.getInputStream()));

        String line = "";
        while ((line = reader.readLine()) != null) {
            output.append(line + "\n");
        }
        System.out.println(output.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }

我还检查了bash文件权限,它可以作为程序执行。

如何运行bash文件? bash应该运行另一个用java编写的程序。

3 个答案:

答案 0 :(得分:0)

- LeBarton什么是退出代码?

检查p.exitValue()

的输出

答案 1 :(得分:0)

p.waitFor()

InputStreamReader inputStreamReader = new InputStreamReader(p.getErrorStream());

While (inputStreamReader.ready()) { System.out.println(inputStreamReader.read(); }

这将显示错误输出。将其添加到try .. catch下面的底部。

您将在命令行中看到输出。它将帮助您缩小错误范围。

答案 2 :(得分:0)

如果你的bash读了一些环境变量,我找到了一个可能有帮助的链接。

$PATH variable isn't inherited through getRuntime().exec