Our team is using the Raspberry Pi. The standard Raspbian OS runs on the device. All code is written in Java.

We are using the Java library package (pi4j). The package listens to the voltage change in GPIO pins.

I want to make Java shut down the Raspberry Pi whenever the Shutdown button is clicked.

Question: how to shut down the Raspberry Pi using Java?

  • Unconfirmed suggestion here.
    – goobering
    Feb 11, 2016 at 13:20
  • 1
    There is no java specific method for this beyond just exec("shutdown"), see here: stackoverflow.com/a/25666/1151724
    – goldilocks
    Feb 11, 2016 at 13:34
  • Goldilocs' answer is better than Runtime.getRuntime().exec("sudo shutdown as it's more portable
    – Havnar
    Feb 11, 2016 at 13:36

1 Answer 1


There looks to be a complete Java example using pi4j here:

import java.io.IOException;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListener;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;

public class Shutdown {

    public static void main(String[] args) throws InterruptedException {
        final GpioController gpio = GpioFactory.getInstance();
        final GpioPinDigitalInput input = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);
        input.addListener(new GpioPinListenerDigital() {

            public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
                System.out.println(event.getPin() + " = " + event.getState());

                //Wenn der Pin#2 auf High geht, fährt sich der Rasperry Pi runter.
                if (input.getState()==PinState.HIGH) {
                    try {
                        Process p = Runtime.getRuntime().exec("sudo shutdown -h now");
                    } catch (IOException | InterruptedException e) {


        while (true) {


  • 2
    you could leave the whole pi4j part out here. Even though Goldilocks answered in a comment, all that is relevant here is Runtime.getRuntime().exec("sudo shutdown -h now");
    – Havnar
    Feb 11, 2016 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.