Java-执行外部Windows应用程序? [英] Java - Execute External Windows Applications?

查看:185
本文介绍了Java-执行外部Windows应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何通过 Java 代码启动外部应用程序(特别是在 Windows 上).我不打算将 Java 代码用于 Mac/Linux ,所以让我们集中讨论 Windows 代码.

我做了什么

最近两天我一直在研究这个问题,但仍然没有找到答案.我很容易找到Runtime.getRuntime().exec()方法,但问题是我找不到从 IntelliJ Idea 中的本地工作区启动批处理(.bat)文件的信息.

我在问什么

我只想知道如何在工作区中执行本地批处理文件(在com.example.batch之类的文件夹中)和/或如何执行(.exe)或(.bat )和直接文件地址. (例如,用于 Windows 碎片整理和优化驱动器(.exe):C:\WINDOWS\system32\dfrgui.exe)

感谢所有人,我一直渴望得到这个答案.

解决方案

您是否已阅读基本的

作为旁注,请查看ProcessBuilder类.它比Runtime好得多.是的,Runtime文章中的所有规则都适用于ProcessBuilder.

I'm unsure how to start an external application (specifically on Windows) through Java code. I'm not planning on using this Java code for Mac/Linux, so let's focus on the Windows code.

What I've Done

I've been researching this question for the last two days, and I still have not found an answer. I easily found the Runtime.getRuntime().exec() method, but the thing is I cannot find information on launching a Batch (.bat) file from my local workspace in IntelliJ Idea.

What I'm Asking

I would just like to know how to execute a local Batch file in my workspace (at a folder like com.example.batch) and/or how to execute a (.exe) or (.bat) with the direct file address. (For example the Defragment and Optimize Drives (.exe) for Windows: C:\WINDOWS\system32\dfrgui.exe)

Thanks to all in advance, I've been dying for this answer.

解决方案

Have you read the essential Runtime.exec() article?

Page 2 of this article lists a common pitfall: Runtime.exec() is not a command line.

.bat files are not executables. They are collections of instructions. Like shell scripts in Linux, you need something to actually execute these instructions.

Your executable in this case is cmd.exe, which will take /C and com.example.batch as its arguments:

Runtime.getRuntime().exec(new String[] { "cmd.exe", "/C", "com.example.batch"});

As a side note, check out the ProcessBuilder class. It's much nicer than Runtime. And yes, all the rules in the Runtime article apply to ProcessBuilder.

这篇关于Java-执行外部Windows应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆