Pregunta

Así que estoy tratando de escribir un archivo .sh que será ejecutable, esta es la forma en que estoy escribiendo actualmente que:

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

Para que escribe el archivo muy bien, pero no es ejecutable. ¿Hay una manera de cambiar el estado ejecutable cuando lo escribo?

Edit: Para aclarar aún más, yo estoy tratando de hacer que ejecute de forma predeterminada, de modo que, por ejemplo, si ha hecho clic doble en el archivo generado, sería ejecutar automáticamente

.
¿Fue útil?

Solución

Se necesitaría a chmod, y es probable que pueda hacerlo por exec'ing un comando del sistema, como por ejemplo:

Realmente todo lo que se necesita es de disparar algo como esto:

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

Sin embargo, si desea realizar un seguimiento de manera más explícita puede capturar la entrada estándar / stderr entonces algo más como:

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

Lo que me dieron desde aquí: http://www.devdaily.com/java/edu/pj/pj010016 /pj010016.shtml

Actualización:

Programa de prueba:

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

}

En Linux si se abre un explorador de archivos y haga doble clic en /tmp/toast.sh y decide ejecutarlo, se debe generar un /tmp/toast.txt archivo de texto con las palabras 'sí tostada'. Asumo Mac haría lo mismo, ya que es BSD bajo el capó.

Otros consejos

You can call File.setExecutable() to set the owner's executable bit for the file, which might be sufficient for your case. Or you can just chmod it yourself with a system call with Process.

Alas, full-powered programmatic alteration of file permissions isn't available until Java 7. It'll be part of the New IO feature set, which you can read more about here.

In Java 7 you can call Files.setPosixFilePermissions. Here is an example:

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

On Mac OS X, besides chmod +x, you have to give a .command extension to your shell script if you want to launch it with a double-click.

This answer I wrote for the question how do I programmatically change file permissions shows a chmod example via a native call using jna, which should work on Mac OS X.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top