javacommandinstallationgksudo

Installing a software from Java Projects with sudo command


what I would like to achieve is installing a software from java application that I
created. I've got permission with gksudo. Then, I typed my pass and the program started working until yes/no option was appeared. How can I pass this question ?

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.io.IOException;


public class TestApp {
public static void main(String[] args) {
     Process ls = null;

    BufferedReader input = null;

    String line = null;

    try {

        ls = Runtime.getRuntime().exec(
                new String[] { "gksudo", "apt-get", "install", "PACKAGE" });
        try {
            ls.wait(6000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ls = Runtime.getRuntime().exec(new String[] { "y" });
        input = new BufferedReader(new InputStreamReader(
                ls.getInputStream()));

    } catch (IOException e1) {
        e1.printStackTrace();
        System.exit(1);
    }

    try {
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }

        ls.destroy();

    } catch (IOException e1) {
        e1.printStackTrace();
        System.exit(0);
    }
  }

  }

Solution

  • Easy - somewhat special - solution: Dont't exec "apt-get install ..." but "apt-get -y install ...". This will suppress any questions for confirmation.

    More general approach: Runtime.exec() creates a process instance. What you are doing in your code is createing two proceses "apt-get" and "y". What you need to do is: Create one process instance and input the character "y" into the input channel of this process. This is achieved by creating the process (as you already do), gather a reference to its input and send "y\n" to this input.

    The input is aquired by calling Process.getOutput() which gives you an OutputStream thats connected to the input of the process.

    This all results in something like:

    ls = Runtime.getRuntime().exec(
                new String[] { "gksudo", "apt-get", "install", "PACKAGE" });
    ls.getOutput().write("y\n".getBytes());