首页 > 解决方案 > 从文件位置运行 Java 中的 .deb 文件

问题描述

所以我需要在我的 JavaFX 程序中的某个时间点运行一个 Debian(.deb) 文件,所以我尝试在 Linux 上使用下面的代码, Runtime.getRuntime().exec("sudo dpkg -i "+pathToResource.getValue().toString());
但正如你已经知道的那样,这需要我还以某种方式传递密码才能使其工作

在 Windows 上,我在这里使用了这个示例代码
Runtime.getRuntime().exec(pathToResource.getValue().toString());
,只要需要管理员权限,软件就会向用户请求它们,一切都会顺利运行

但这似乎在 Linux 上不起作用,它只是静默,什么也没有发生,
我已经有了尝试使用 TerminalFx 的替代方法,但是如果有人知道运行 .deb 文件的替代方法或任何其他替代方法,我会很感激的。提前致谢。

标签: javafxdebian

解决方案


所以我最终使用了 shellScript

这就是我所做的

  1. 通过只有一个文本字段和一个提交按钮的简单 JavaFX 阶段向用户请求设备密码。
  2. 然后我使用刚刚从用户那里获得的密码创建了一个 shell 脚本(Bash)

这是我创建示例 shell 脚本的示例代码

File shell_file = new File("path_to_the_file_where_the_shell_file_will_be_created_at_example_install.sh");
String variableName = "#!/bin/bash\npassword='" + password_from_JavaFx_stage + "'\n" +
                        "echo $password | sudo -S dpkg -i " + path_to_file_to_be_installed;

shell_file.createNewFile()// you can put an if  to check if the function worked and otherwise do some other actions

FileWriter myWriter = new 
FileWriter("path_to_the_file_where_the_shell_file_will_be_created_at_example_install.sh");
myWriter.write(messageContent);
myWriter.close();

然后只需使用 Processbuilder 运行命令,这是一个示例代码

String[] command = {String.valueOf(shell_file)};
ProcessBuilder processBuilder = new ProcessBuilder().command(command);
try {
      Process process = processBuilder.start();

      //read the output
      InputStreamReader inputStreamReader = new 
      InputStreamReader(process.getInputStream());
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String output = null;
                  
      while ((output = bufferedReader.readLine()) != null) {
        System.out.println(output);
      }
      process.waitFor();

      //close the resources
      bufferedReader.close();
      process.destroy();

}catch(IOException | InterruptedException e) {
      e.printStackTrace();
}

所以这就是想法,这是我最大的希望,这将节省某人的时间并以某种方式提供帮助。


推荐阅读