Running shell script from java code and pass arguments

前端 未结 4 1608
走了就别回头了
走了就别回头了 2020-12-12 04:40

I am executing a shell script from Java program. I have implemented it using Runtime class. Below is the code I implemented

final StringBuilder sb = new Stri         


        
相关标签:
4条回答
  • 2020-12-12 05:08

    Use this:

    final StringBuilder sb = new StringBuilder("test.sh");
    sb.append(" \"/path to/my/text file\"");
    
    0 讨论(0)
  • 2020-12-12 05:09

    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());
    
    0 讨论(0)
  • 2020-12-12 05:10

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

    0 讨论(0)
  • 2020-12-12 05:13

    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();
    
    0 讨论(0)
提交回复
热议问题