Java Runtime exec 不抛出此类文件或权限被拒绝 [英] Java Runtime exec throws no such file or permission denied

查看:39
本文介绍了Java Runtime exec 不抛出此类文件或权限被拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序在 ubuntu 10.04 上运行,代码如下:

My program is running on ubuntu 10.04 ,and here is the code :

Process process=Runtime.getRuntime().exec("ls",null,null);

它抛出一个异常:

Cannot run program "ls": java.io.IOException: error=2, No such file or directory,  

我尝试将ls"更改为chmod"、pwd",我发现没有一个shell命令可以工作,都遇到了同样的问题.(我也尝试过/bin/sh -c ls")

and i tried to change "ls " to "chmod" ,"pwd" ,i found no one shell command work, all came to the same problem .(I also tried "/bin/sh -c ls")

然后我将代码更改为:

Process process=Runtime.getRuntime().exec("/bin/ls",null,null);

它抛出一个异常:

Cannot run program "/bin/ls": java.io.IOException: error=13, Permission denied

我已将所有相关文件和目录的权限更改为 777,所以我真的不知道它有什么问题.

I have changed privilege of all the related files and directories to 777 so i really don't know what's wrong with it.

感谢您的回复.

推荐答案

Process process=Runtime.getRuntime().exec("ls",null,null);

这会导致 No such file or directory 异常,因为 ls 很可能不在程序的当前工作目录中.当您在 Linux shell 提示符下键入 ls 时,它使用 PATH 环境变量将 ls 转换为 /bin/ls.Runtime 不会为您执行此操作.

This is expected give a No such file or directory exception since ls is most likely not in the current working directory of your program. When you type ls from the Linux shell prompt, it uses the PATH environment variable to turn ls into /bin/ls. Runtime does not do this for you.

您需要指定完整路径"/bin/ls".正如@Ernest 提到的,您应该使用 Runtime.exec("/bin/ls") 方法,而不是传入空参数.

You need to specify the full path "/bin/ls". As @Ernest mentioned, you should be using the Runtime.exec("/bin/ls") method and not passing in the null arguments.

Process process=Runtime.getRuntime().exec("/bin/ls");

您的评论似乎表明,即使您使用此调用,您也会收到 Permission denied 异常.这适用于标准 Java 可执行文件.我假设您可以从 Linux 命令行成功执行 /bin/ls ?/bin/ls(和相关目录)应该是 755 而不是 777,这将是一个安全噩梦.但是 777 应该可以.

Your comments seem to indicate that even when you use this call, you are getting a Permission denied exception. This works for me from a standard Java executable. I assume that you can do a /bin/ls from the Linux command line successfully? /bin/ls (and the associated directories) should be 755 and not 777 which would be a security nightmare. But 777 should work.

也许您正在运行某种受保护的 JDK?例如,出于安全原因,小程序没有执行 Unix 命令的权限.也许您有一个限制性的 Java 策略文件 需要添加execute权限吗?

Maybe you are running some sort of protected JDK? Applets, for example, do not have permissions to execute Unix commands for security reasons. Maybe you have a restrictive Java policy file and you need to add execute permissions?

这篇关于Java Runtime exec 不抛出此类文件或权限被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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