我正在尝试从Java运行一个Linux命令。该命令在命令行本身运行得很好,但在Java中却不是。命令行中的命令是
curl -H "Content-Type: text/plain" -d "$(printf '#Genes\nPIK3C2A\nPTEN\nUNC5B')" -X POST --url https://reactome.org/AnalysisService/identifiers/projection/来自Java的命令是
String $notifyMsg="\"$(printf '#Genes\nPIK3C2A\nPTEN\nUNC5B')\"";
String $reactome = "https://reactome.org/AnalysisService/identifiers/projection/";
String $notifyTitle= "\"Content-Type: text/plain\"";
String $command = "curl" + " " + "-H"+ " " + $notifyTitle + " "+ "-d " + $notifyMsg +" "+ "-X" + " " + "POST" + " " + " " + "--url" +" " + $reactome;
System.out.println("Command is: " + $command);
Process p=Runtime.getRuntime().exec($command);
p.waitFor();
System.out.println("Run Result " + p.exitValue() )我被认为能得到这样的输出
{"summary":{"token":"MjAxODAxMjMxNjQyMDZfNjcy","projection":true,"interactors":false,"type":"OVERREPRESENTATION","sampleName":"Genes","text":true},"expression":{"columnNames":[]},"identifiersNotFound":0,"pathwaysFound":51,"pathways":但我得到的是0。有人能告诉我怎么回事吗?
发布于 2018-01-28 18:06:36
引用和逃避是你的敌人。最好的办法就是完全避开他们。使用一个方法启动该进程,该方法允许您将单个参数作为单独的字符串传递,而不必将它们分开。
Process p = new ProcessBuilder(
"curl",
"-H", "Content-Type: text/plain",
"-d", "#Genes\nPIK3C2A\nPTEN\nUNC5B",
"-X", "POST",
"--url", "https://reactome.org/AnalysisService/identifiers/projection/"
).start();您的代码调用exitValue(),这将为您提供流程的退出代码。若要读取其输出,请从其输入流读取。
InputStream s = p.getInputStream();发布于 2018-01-28 18:08:33
p.exitValue()将为您提供流程的退出代码。它返回0,因为curl使用退出代码0成功。
我会考虑查看图书馆,以便在Java中本机执行这些操作。
发布于 2018-01-28 18:13:43
这就是对我有用的东西:
String notifyMsg = "#Genes\nPIK3C2A\nPTEN\nUNC5B";
String reactome = "https://reactome.org/AnalysisService/identifiers/projection/";
String notifyTitle = "Content-Type: text/plain";
Process p = new ProcessBuilder("curl", "-H", notifyTitle, "-d", notifyMsg, "-X", "POST", "--url", reactome).start();
p.waitFor();
try (Scanner scanner = new Scanner(new InputStreamReader(p.getInputStream()))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
System.out.println("Run Result " + p.exitValue());ProcessBuilder的vararg构造函数Content-Type指令和-d中有额外的双引号$(printf是shell解释的东西,但Java没有解释。只需使用Java文本中的\n来获得新行即可。我还添加了一些代码来读取输出。
https://stackoverflow.com/questions/48489633
复制相似问题