从Java程序启动蒸汽游戏

时间:2015-02-21 23:00:22

标签: java

我正在尝试制作一个java程序来打开我的PC上的文件和应用程序,现在问题只出现在我尝试从这个程序打开一个蒸汽游戏(即Planetside 2或Terraria)时。我尝试过使用Runtime,但也失败了。这是我试图打开游戏的地方:

public void mousePressed(MouseEvent e) {
        try {
            Desktop.getDesktop().browse(new URL(path).toURI());
        } catch (URISyntaxException | IOException e1) {
            try {
                Desktop.getDesktop().open(new File(path));
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            e1.printStackTrace();
        }
    }

如果有人可以尝试解决这个问题,我们将不胜感激!

这是输出错误:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: steam:\rungameid\218230 doesn't exist.

路径变量是" steam:// rungameid / 218230"。

1 个答案:

答案 0 :(得分:0)

您必须通过Steam.exe来指示app id进程打开游戏,或者可以使用steam协议:

import lombok.val;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;

import static java.awt.Desktop.getDesktop;
import static java.util.Arrays.asList;

public class SteamGameExecutor
{
    public static final String STEAM_INSTALLATION_PATH = "C:\\Program Files (x86)\\Steam\\Steam.exe";
    private static final boolean USE_STEAM_PROTOCOL = true;

    public static void startGameById(String id) throws Exception
    {
        if (USE_STEAM_PROTOCOL)
        {
            val desktop = getDesktop();
            val steamProtocol = new URI("steam://run/" + id);
            desktop.browse(steamProtocol);
        } else
        {
            startProcess("-applaunch", id);
        }
    }

    private static void startProcess(String... arguments) throws IOException
    {
        val allArguments = new ArrayList<String>();
        allArguments.add(STEAM_INSTALLATION_PATH);
        val argumentsList = asList(arguments);
        allArguments.addAll(argumentsList);
        val process = new ProcessBuilder(allArguments);
        process.start();
    }
}

除非版本Linux / Mac上不存在,否则协议版本应更具可移植性/与平台无关。

要找到app id,可以使用this搜索。例如,以编程方式找到应用ID的实现如下:

import lombok.val;

import java.io.IOException;

import static java.net.URLEncoder.encode;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.jsoup.Jsoup.connect;

public class SteamAppIdFinder
{
    private static final String SEARCH_URL = "https://steamdb.info/search/?a=app&q=";
    private static final String QUERY_SELECTOR = "#table-sortable > tbody > tr > td:nth-child(1) > a";

    public static String getAppId(String searchTerm) throws IOException
    {
        val completeSearchURL = SEARCH_URL + encode(searchTerm, UTF_8.name());
        val connection = connect(completeSearchURL);
        val document = connection.get();
        val selectedElements = document.select(QUERY_SELECTOR);
        val anchorElement = selectedElements.get(0);
        return anchorElement.text();
    }
}

请注意,第二个代码段需要JSoup。此外,我在val关键字中使用了Lombok