Running shell script from java code and pass arguments

偶尔善良 提交于 2019-11-28 14:31:07

Use ProcessBuilder , it's what it's designed for, to make your life easier

ProcessBuilder pb = new ProcessBuilder("test.sh", "/path", "/my/text file");
Process p = pb.start();

Use this:

final StringBuilder sb = new StringBuilder("test.sh");
sb.append(" \"/path to/my/text file\"");

To recreate the command you run in shell manually, test.sh "/path to/my/text file", you will need to include the quotes.

final StringBuilder sb = new StringBuilder("test.sh");
sb.append(" \"/path to/my/text file\""); //notice escaped quotes
final Process p = Runtime.getRuntime().exec(sb.toString());

Your approach is correct you just need to add a space (" ") before parameters and escape the "/" and " " characters in the parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!