Java运行命令行,其中包含空格 [英] Java run command line which contains spaces

查看:88
本文介绍了Java运行命令行,其中包含空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Java应用程序运行.bat文件.我已经尝试了所有可以找到的方法,但是似乎都没有用.

I'm trying to run a .bat file from my Java app. I've tried all the methods I could find, but none seems to work.

问题是.bat文件的路径包含空格.

The problem is that the path to the .bat file containing spaces.

我正在使用方法,现在我可以在Eclipse控制台中查看结果

I'm using this method now so I can see the results in my Eclipse console

我的实际代码是:

Runtime rt = Runtime.getRuntime();
String processString = "cmd /c \"" + homeFolder.getAbsolutePath() + SETUP_FILE + "\" \"" + homeFolder.getAbsolutePath() + "\"";
    try {
        Process proc = rt.exec(processString);
    ...
    }

我已经尝试过将引号转义,而不将引号转义,将字符串分成String[]并将每个空格分隔的命令放在自己的单元格中:

I've tried with escaping the quotes, without escaping quotes, separating the string into String[] and placing each space separated command its own cell:

{ "cmd", "/c", \"" + homeFolder.getAbsolutePath() + SETUP_FILE + "\" ... };

同样,带引号和不带引号:无效.

Again, with and without escaping the quotes: nothing works.

我也尝试过硬编码到数组和字符串的路径.每次都有相同的结果.

I also tried hard-coding the paths to both the array and the string. Same results every time.

homeFolder = C:\Users\La bla bla\workspace\ToolMaker\bin\
SETUP_FILE = setup.bat

整个命令是这样的:

cmd /c "C:\Users\La bla bla\workspace\ToolMaker\bin\setup.bat" "C:\Users\La bla bla\workspace\ToolMaker\bin"

再次使用带引号或不带引号的结果相同:

Again, with or without quotes, same output:

Output: 
Error: 'C:\Users\La' is not recognized as an internal or external command,operable program or batch file.

很明显,我在Windows(7位64位专业版)上运行. Java 7

Obviously I'm running on Windows (7, 64 bit professional). Java 7

我看到一些人说他们以前有这个问题,但是我找不到解决该问题的答案.

I saw a few people said they had this issues before, but I couldn't find an answer on how to get around that.

推荐答案

使用

这对我有效(Win7):

This works for me (Win7):

Runtime rt = Runtime.getRuntime();
String[] processCommand = { "cmd", "/c", "c:" + File.separatorChar + "dir with spaces" + File.separatorChar + "test.bat" };

System.out.println("xPATH: " + processCommand[2]);

Process p = rt.exec(processCommand);
// output of the command is as expected

如果我明确使用\,这也将起作用:

This also works if I use \ explicitly:

String[] processCommand = { "cmd", "/c", "c:\\dir with spaces\\test.bat" };

这篇关于Java运行命令行,其中包含空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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