尝试使用java在shell上运行命令时,Process.execute()会抛出异常 [英] Process.execute() throws exception when trying to run command on shell using java

查看:532
本文介绍了尝试使用java在shell上运行命令时,Process.execute()会抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了这个代码,它应该在shell上执行一个命令来搜索文本文件中的模式>,当我在shell上尝试相同的命令它工作正常但是当我尝试使用java执行相同的命令时,它不会为我工作作为缓冲读者返回null。可以告诉我在这方面我做错了。

I have written this code which should execute a command on shell to search pattern ">" in a text file , when I try same command on shell it works fine but when I try execute same command using java , it doesn't work for me as buffered reader returns null.Can somebody tell that what I have done wrong in this.

代码:

            String filename="/home/abhijeet/sample.txt";

            Process contigcount_p;

            String command_to_count="grep  \">\" "+filename+" | wc -l";

            System.out.println("command for counting contigs "+command_to_count); 

            contigcount_p=Runtime.getRuntime().exec(command_to_count);


             contigcount_p.wait();


            BufferedReader reader = 
                        new BufferedReader(new InputStreamReader(contigcount_p.getInputStream()));    

            System.out.println("chkk buffer"+reader.readLine());


推荐答案

根据评论我通过包装命令解决了这个问题在shell中使用

According to comments i have resolved thsi issue by wrapping commands in a shell by using

Runtime.getRuntime().exec(new String[]{"sh", "-c", "grep  \">\" "+filename+" | wc -l"});

通过此命令执行成功但我仍然无法通过bufferedreader获取其输出,仍然输出值为NULL,所以我所做的是我在第一个命令中将它的输出清除为临时文件

By this command was executing successfully but i was still not able to get its output by bufferedreader , as still output value was NULL, so what i have done is that i in first command i have redicted it's output to a temporary file

 Runtime.getRuntime().exec(new String[]{"sh", "-c", "grep  \">\" "+filename+" | wc -l > temp"});

我又创建了一个进程来执行此命令的读取,然后删除该临时文件。

and I have created one more process to execute a read on this command and then to remove that temporary file.

请参阅: - shell命令执行从Java执行时失败

注意:我知道这不是一个完美的解决方案应该可以直接通过bufferedreader获得,但可以找到任何解决方案,任何答案仍然是欢迎的,出于临时目的我已经使用此答案将删除并接受答案,如果有人为此提供解决方案。

Note: I know that this is not a perfect solution for this as output should be directly available by bufferedreader, but could'd find any solution yet, Any answer is still welcom, for temporary purpose i have used this answer will remove and accept answer if someone gives a solution for this.

这篇关于尝试使用java在shell上运行命令时,Process.execute()会抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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