Write an executable .sh file with Java for OSX

后端 未结 5 1313
情书的邮戳
情书的邮戳 2021-01-18 00:59

So I am trying to write an .sh file that will be executable, this is how I\'m currently writing it:

Writer output = null;

try {
  output = new BufferedWrite         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-01-18 01:28

    You'd need to chmod it, and you can probably do it by exec'ing a system command like such:

    Really all you'd need is to fire off something like this:

    Runtime.getRuntime().exec("chmod u+x "+FILENAME);
    

    But if you want to keep track of it more explicitly can capture stdin / stderr then something more like:

    Process p = Runtime.getRuntime().exec("chmod u+x "+FILENAME);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));    
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    

    Which I got from here: http://www.devdaily.com/java/edu/pj/pj010016/pj010016.shtml

    Update:

    Test program:

    package junk;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.Writer;
    
    public class Main{
      private String scriptContent = '#!/bin/bash \n echo "yeah toast!" > /tmp/toast.txt';
      public void doIt(){
        try{
          Writer output = new BufferedWriter(new FileWriter("/tmp/toast.sh"));
          output.write(scriptContent);
          output.close();
          Runtime.getRuntime().exec("chmod u+x /tmp/toast.sh");
        }catch (IOException ex){}
      }
    
      public static void main(String[] args){
        Main m = new Main();
        m.doIt();
      }
    
    }
    

    On linux if you open up a file browser and double click on /tmp/toast.sh and choose to run it, it should generate a text file /tmp/toast.txt with the words 'yeah toast'. I assume Mac would do the same since it's BSD under the hood.

提交回复
热议问题