Black
Black

Reputation: 81

Write to a file using commands through java program on Mac OS X

I am trying to write a variable to ~/.bash_profile using commands like echo, but I am unable to write it to the file. I tried the following,

Runtime run = Runtime.getRuntime();
    String line = null;
    try {
        Process pr = run.exec("echo \"export ANDROID_HOME=/Users/abc/Documents/platform-tool\" >> ~/.bash_profile");
        pr.waitFor();
        BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        while ((line = buf.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        logger.error("Error occurred when getting adb " + e.getMessage());
    } catch (InterruptedException ie) {
        logger.error("Error occurred when getting adb " + ie.getMessage());
        Thread.currentThread().interrupt();
    }

I also tried giving ' instead of \" and just echo export still it is not writing to that file. When I try to print the output it prints

"export ANDROID_HOME=/Users/abc/Documents/platform-tool" >> ~/.bash_profile

But the file is empty.

I also tried using printf but that again does not work. Also these commands do work in terminal but using in java, it is not writing to the file.

Any help would be appreciated and if there are other methods than which I'm using please suggest

Upvotes: 2

Views: 234

Answers (1)

Amadan
Amadan

Reputation: 198418

When you do echo foo >> bar in Terminal, there are two important differences:

  • echo is an built-in bash command (as opposed to /bin/bash that can be found in PATH) - but that's not very important, since the two behave the same; and

  • >> is processed by bash and not given to echo as a parameter to print. It is bash that handles parsing the command line, handling redirection, and a bunch of other things like handling variable substitution. In this case, Java parses the command line, and hands them directly to the program.

So in essence, you're executing:

'/bin/echo' '"export ANDROID_HOME=/Users/abc/Documents/platform-tool\"' '>>' '~/.bash_profile'

If you try that in Terminal, it will do the same thing your Java-invoked echo did.

In order to do what you want, you would need to run a shell (e.g. bash) to handle the redirection:

run.exec("bash -c 'echo \"export ANDROID_HOME=/Users/abc/Documents/platform-tool\" >> ~/.bash_profile'")

However, a natural question to pose here is - why use Java to invoke bash to call echo...? Why not just use Java? (How to append text to an existing file in Java)

Upvotes: 3

Related Questions