Home > Enterprise >  How to execute bash commands in Java (Raspberry pi)
How to execute bash commands in Java (Raspberry pi)

Time:09-29

I dont know why, but I can only execute a very small pallet of commands on my Raspberry 3B from code (I cane even execute echo). For some reason, 99% of the commands that you would normally be able to do in the terminal itself, you cant do from code.

Example: I execute this java code: Runtime.getRuntime().exec("echo hi");

And I get this: `java.io.IOException: Cannot run program "echo hi": error=2, No such file or directory

Is there a PATH configuration that I dont have access to in java code? why cant I execute any commands to the raspberry pi from code?

CodePudding user response:

I've written some example that uses the exec() call. There are other methods to start processes from within Java (ProcessBuilder is the keyword here), but this example is relatively easy to understand:

import java.util.*;
import java.io.*;
import java.text.*;

public class X {

    public static void main(String argv[])
    {
        String args[] = { "/bin/bash", "-c", "uptime" };
        try {
            Process p = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = in.readLine();
            while (line != null) {
                System.out.println("Found: "   line);
                line = in.readLine();
            }
        } catch (Exception e) {
            System.err.println("Some error occured : "   e.toString());
        }
    }

}

Basically the program executes the command line /bin/bash -c uptime; just an uptime would have done the same, but I wanted to show how to work with command line arguments for the program to start.

  • Related