我需要你的帮助才能知道我的错误在哪里:)
public class Main extends JFrame{
public Main() {
EventQueue.invokeLater(new Runnable() {
public void run() {
setVisible(true);
}
});
}
public static void main(String[] args) throws IOException, URISyntaxException {
new Main();
File executor = File.createTempFile("Executor", ".sh");
PrintWriter writer = new PrintWriter(executor, "UTF-8");
writer.println("#!/bin/bash");
writer.println();
writer.println("java -$* > /tmp/output.txt 2>&1 &"); // ***
writer.close();
executor.setExecutable(true); // ***
File elevator = File.createTempFile("Elevator", ".sh");
writer = new PrintWriter(elevator, "UTF-8");
writer.println("#!/bin/bash");
writer.println();
writer.println(String.format("osascript -e \"do shell script \\\"%s $*\\\" with administrator privileges\"",
executor.getPath()));
writer.close();
elevator.setExecutable(true); // ***
Runtime.getRuntime().exec(String.format("%s -cp %s Main param", // ***
elevator.getPath(),
Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()));
}
}
此代码假设使用管理员权限运行应用程序新时间。 系统会询问管理员密码,但之后,应用程序无法运行。 为什么?我的输出中没有错误
谢谢
答案 0 :(得分:1)
我知道我的问题在哪里! 这一行:
writer.println("java -$* > /tmp/output.txt 2>&1 &");`
必须删除 - 在$ *
之前writer.println("java $* > /tmp/output.txt 2>&1 &");
它有效!对于像我这样搜索如何在MAC OS X上为您的JAVA应用程序启用管理员权限的所有人,您现在拥有代码!
此代码完美无缺!
File executor = File.createTempFile("Executor", ".sh");
PrintWriter writer = new PrintWriter(executor, "UTF-8");
writer.println("#!/bin/bash");
writer.println();
writer.println("java $* > /tmp/output.txt 2>&1 &");
writer.close();
executor.setExecutable(true);
File elevator = File.createTempFile("Elevator", ".sh");
writer = new PrintWriter(elevator, "UTF-8");
writer.println("#!/bin/bash");
writer.println();
writer.println(String.format("osascript -e \"do shell script \\\"%s $*\\\" with administrator privileges\"",
executor.getPath()));
writer.close();
elevator.setExecutable(true);
Runtime.getRuntime().exec(String.format("%s -cp %s Main param",
elevator.getPath(),
Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()));
享受!