我将如何使用Java运行.sh文件并获取其输出?

可能重复:
Java代码来执行.sh文件

我使用/root/new_scripts/setpermission.sh一个参数将代码写入.sh文件并运行它: setpermission.sh包含:

 chmod 777 $1 

它通过键入/root/new_scripts/setpermission.sh位置从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(); } 

请发布您正在使用的Java代码来尝试此操作。 但是,通过做一些假设,您可能需要找到并使用完全限定的路径来“sh”,因为Java ProcessBuilder不会使用设置的“PATH”环境变量。