You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Runtime.getRuntime().exec在GitHub Actions中失败,本地运行正常求助

问题:Java获取设备电量工具在GitHub Actions中测试失败

我正在开发一个使用Java获取设备电量的工具,已在Windows、Mac、Linux(Ubuntu和树莓派)本地测试通过,单元测试也能正常运行,但在GitHub Actions中执行时失败,原因不明。该Java代码通过执行终端命令实现功能。

Java核心代码

import nl.altindag.senzu.exception.SenzuException;
import nl.altindag.senzu.util.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;

public abstract class TerminalBatteryInfoProvider implements BatteryInfoProvider {

    @Override
    public Optional<String> getBatteryLevel() {
        String[] command = getCommand();
        try(InputStream inputStream = createProcess(command).getInputStream()) {
            String content = IOUtils.getContent(inputStream);

            return Stream.of(content.split(System.lineSeparator()))
                    .map(String::trim)
                    .filter(line -> !line.isEmpty())
                    .filter(getFilter())
                    .map(getMapper())
                    .findFirst();
        } catch (IOException e) {
            throw new SenzuException(e);
        }
    }

    private static Process createProcess(String[] command) {
        try {
            return Runtime.getRuntime().exec(command);
        } catch (IOException e) {
            throw new SenzuException(e);
        }
    }

    protected abstract String[] getCommand();

    protected abstract Predicate<String> getFilter();

    protected abstract Function<String, String> getMapper();

}

各系统执行命令

  • Windows:new String[]{"WMIC", "PATH", "Win32_Battery", "Get", "EstimatedChargeRemaining"}
  • Mac:new String[]{"system_profiler", "SPPowerDataType"}
  • Linux/Ubuntu:new String[]{"bash", "-c", "upower -i /org/freedesktop/UPower/devices/battery_BAT0"};

GitHub Action配置

name: Build

on:
  push:
    branches:
      - master
  pull_request:

jobs:
  build:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ ubuntu-latest, windows-latest, macos-latest ]
        java: [ '8', '11', '17', '21' ]
    steps:
      - uses: actions/checkout@v2

      - name: Set up JDK
        uses: actions/setup-java@v3
        with:
          distribution: 'zulu'
          java-version: ${{ matrix.java }}
          cache: 'maven'

      - name: Build and test
        run: mvn clean verify --no-transfer-progress

疑问

是否是GitHub Actions缺少命令执行权限?或有什么方法可以排查问题原因?


内容的提问来源于stack exchange,提问作者Hakan54

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:55:10