通过ProcessBuilder传递字符串到批处理文件

3

我正在使用Java ProcessBuilder将一个字符串作为参数传递给批处理文件。

ProcessBuilder pb = new ProcessBuilder( "batch.bat", "jason mary molly");

批处理文件...

 @ECHO OFF
 SET V1=%1
 ECHO %V1%
 pause

批处理文件输出如下(注意双引号):

"jason mary molly"

如果我只传入一个字符串,就找不到引号了!我的问题是,我正在编写一个相当复杂的程序,需要这3个参数没有双引号,否则它们将被视为一个文件名而不是3个单独的参数。有没有办法去掉这些双引号?
2个回答

2

尝试使用:%~1,这样可以去掉引号。

要获取更多信息,请在cmd中键入:for /? | more +121。这里是引用的参考:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

这些修饰符可以组合使用,以获得复合结果:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
               environment variable for %I and expands to the
               drive letter and path of the first one found.
%~ftzaI     - expands %I to a DIR like output line

1
好的,现在如果你能回答为什么我没有在2小时前发布这个?它起作用了!非常感谢。 - Jason
我打算这样做,只需要再等几分钟,然后它就会让我操作了 :) - Jason
哦,是的,忘记了时间机制。谢谢。 - Monacraft

1
每个传递给ProcessBuilderString都成为您正在执行的命令的参数,因此使用它们时要小心。
ProcessBuilder pb = new ProcessBuilder( "batch.bat", "jason mary molly");

这意味着您向命令传递了1个参数,而不是三个。

尝试使用...

ProcessBuilder pb = new ProcessBuilder( "batch.bat", "jason", "mary", "molly");

相反


谢谢回复,但我没有将参数作为单独参数传递的选项。 - Jason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接