【问题标题】:Open a file with its associated application and extra command line parameters打开带有关联应用程序和额外命令行参数的文件
【发布时间】:2020-06-03 20:39:19
【问题描述】:

我想打开一个包含相关应用程序和几个命令行参数的文件。

例如the_app.exe -someoption file.appthe_app.exe 是用于打开.app 文件的关联应用程序。

我正在寻找 Desktop 课程,希望能找到其中一个

  • Desktop.getDesktop().open(file,options),或
  • Desktop.getDesktop().getOpenFileHandler(file),然后在此基础上使用 ProcessProcessBuilder

都不存在。还有什么建议吗?

【问题讨论】:

  • 如果您不知道将用于打开文件的应用程序是什么,您怎么知道要使用哪些选项?

标签: java file exec


【解决方案1】:

在java中你可以使用Runtime来运行程序。

Runtime.getRuntime().exec("program");

您也可以使用“cmd”来运行命令行命令。

然后,如果不需要选项参数,您可以简单地使用“启动”命令。

//this will open notepad in my pc
Process pr = Runtime.getRuntime().exec("cmd /c start test.txt");

如果你真的需要传递命令,你可以使用一些辅助命令并构建你自己的命令行:

使用“assoc”可以检索文件类型

使用 'ftype' 您可以检索文件类型的应用程序

然后:

private static String command(Runtime rt, String command) throws IOException {
    Process pr = rt.exec("cmd /c " + command);
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getInputStream()))){
        return reader.readLine();
    }
}

public static void main(String[] args) throws IOException {
    //without parameters is an easy job
    Process pr = Runtime.getRuntime().exec("cmd /c start test.txt");

    //with parameters things get messy
    Runtime rt = Runtime.getRuntime();
    String out1 = command(rt, "assoc .txt");
    System.out.println(out1);
    String assoc = out1.split("=")[1];
    String out2 = command(rt, "ftype " + assoc);
    System.out.println(out2);
    String app = out2.split("=")[1].split(" ")[0]; //error prone, consider using regex
    command(rt, app + " /P test.txt"); //This will print (/P) the file using notepad

}

当然,这些都不是便携式的。

更多信息:

Running Command Line in Java

Best way to get file type association in Windows 10 from command line?

https://www.addictivetips.com/windows-tips/file-app-association-command-prompt-windows-10/

How to open file with default application in cmd?

【讨论】:

  • 与我上周开始输入并随后丢弃的答案完全相同,因为我意识到 1. 在 ftype 中分配的命令的语法远非标准并且从中运行的实际命令是,如你说,容易出错; 2. 如果 OP 知道将哪些参数传递给关联的应用程序......这意味着他们已经知道它是哪个应用程序,所以不需要任何这些。 (但无论如何 +1。)
  • 谢谢。无论如何,“assoc”命令返回一个空值,而(在 Win7 中)资源管理器识别文件类型(在我的情况下为“mscz”文件,(“压缩 MuseSocre 文件”)。Assoc 不应返回空值。进行调查。关于您已经知道要使用的应用程序的评论,是的,我确实知道。但我不知道它的安装位置和名称(名称可能与版本不同,位置是唯一的(操作系统,...)) .
  • 这很奇怪..你还记得'。' (点)在扩展之前? (我的意思是“assoc .mscz”)您也可以不带任何参数运行“assoc”来查看所有关联。
  • 我做到了。扩展名不在完整的“assoc”命令中,其文件类型也不在完整的“ftype”命令中。
  • 应用程序在注册表中的注册方式可能有问题...无论如何谢谢
猜你喜欢
  • 2011-06-28
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多