【问题标题】:How do I send a command through cmd in Java?如何在 Java 中通过 cmd 发送命令?
【发布时间】:2014-04-22 04:00:48
【问题描述】:

这是我的两难境地:我正在尝试制作一个命令行 Java 程序,并且我希望其中一项功能是调用记事本来打开文件。现在我知道您可以通过 CMD 执行此操作,例如

notepad "filename.txt"

我知道您可以在 VB 中使用 Shell() 或在 .NET 中使用 Process.Start()。

但是,有没有办法从 Java 中做到这一点?我会明白为什么不这样做,因为它是跨平台的,而且这种方式违背了目的,但是(知道如何)实现它会很棒。

【问题讨论】:

  • 如果你出于某种原因想强制记事本; Runtime.getRuntime().exec("notepad whatever.txt");——但使用上述链接帖子中的答案会更便携,如果用户配置了不同的首选编辑器,可能会有更好的 UX 不强迫用户使用记事本。

标签: java process cmd command


【解决方案1】:

这是一个使用 Runtime.getRuntime().exec() 的快速示例。

import java.io.IOException;
import java.util.Scanner;

public class SOTest
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("File Name: ");

        // Get the file path and close scanner
        String file = in.next();
        in.close();

        try
        {
            Runtime.getRuntime().exec("notepad " + file);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 2021-05-18
    • 2014-07-31
    相关资源
    最近更新 更多