Write Java. OSX .sh executable

So, I am trying to write a .sh file that will be executable, this is how I am writing it now:

Writer output = null;

try {
  output = new BufferedWriter(new FileWriter(file2));
  output.write(shellScriptContent);
  output.close();
} catch (IOException ex) {
  Logger.getLogger(PunchGUI.class.getName()).log(Level.SEVERE, null, ex);
}

Thus, the file is written just fine, but it is not executable. Is there a way to change the executable status when I write it?

Edit: for further clarification, I try to execute it by default, so that, for example, if you double-click the generated file, it will be automatically executed.

+5
source share
5 answers

You will need chmod, and you can possibly do this by running a system command like:

Indeed, all you need to do is knock down something like this:

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

, stdin/stderr, - :

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()));

: http://www.devdaily.com/java/edu/pj/pj010016/pj010016.shtml

Update:

:

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();
  }

}

Linux, /tmp/toast.sh , /tmp/toast.txt ", ". , Mac , BSD .

+9

File.setExecutable(), , . chmod Process.

, Java 7. New IO, .

+16

Mac OS X, chmod + x, .command script, .

+2

chmod jna, Mac OS X.

+1

Java 7 Files.html#setPosixFilePermissions. :

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Set;

class FilePermissionExample {
  public static void main(String[] args) throws IOException {
    final Path filepath = Paths.get("path", "to", "file.txt");
    final Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(filepath);
    permissions.add(PosixFilePermission.OWNER_EXECUTE);
    Files.setPosixFilePermissions(filepath, permissions);
  }
}
+1

All Articles