这个问题已经在这里有了答案:




9年前关闭。






我使用/root/new_scripts/setpermission.sh中的一个参数在.sh文件中编写代码,然后运行它:setpermission.sh包含:

chmod 777 $1

通过输入/root/new_scripts/setpermission.sh location从Linux控制台成功执行了该操作。但是当我尝试使用以下代码使用Java代码运行它时:
Java完整代码:
String fileLocation = BASE_DIR + domain + SUB_DIR_CAKE + fileName;
    File newFile = new File(fileLocation);
    System.out.println("Permission file location: " + fileLocation);
    if(newFile.exists()) {
        String command;
        String[] commandArray;
        command = "/root/new_scripts/setpermission.sh";
        File commandFile = new File(command);
        if(commandFile.exists()) {
            System.out.println("\n\n\n\n\nFILE EXISTS");
        } else {
            System.out.println("\n\n\n\n\nFILE NOT EXISTS");
        }
        commandArray = new String[]{"/bin/sh", command, newFile.toString()};
        try {
            Process p = Runtime.getRuntime().exec(commandArray);
            return "HERE OK";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    } else {
        return "file not exists";
    }

它返回HERE OK

最佳答案

尝试这个:

            String command;
            String[] commandArray;


            command = "./new_scripts/setpermission.sh";
            commandArray = new String[]{"/bin/sh", command, fileLocation, permission};
          try {

              Process p = Runtime.getRuntime().exec(commandArray);

         } catch (Exception e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        }

07-24 18:37
查看更多