繁体   English   中英

在Java中使用空格运行外部exe

[英]running external exe with spaces in java

我已经尝试了4个小时才能运行此程序,但我却不理解为什么这样做://

我用GUI创建了一个非常简单的Java程序,其中包含2个文本框,人们可以在其中键入exe文件的路径。 单击按钮后,它将读取此框中的文本并运行相应的软件。

当人们在目录框中键入“ C:\\ Program Files(x86)\\ thatsoftware \\”,并在要运行的文件中键入“ C:\\ Program Files(x86)\\ thatsoftware \\ run this.exe -arg”时,这似乎起作用框:

Runtime.getRuntime().exec(txtFile.getText().toString(), null, new File(txtPath.getText().toString()));

但是,当我仅设置1个目录框并附加(硬编码)文件和参数时,它将不起作用:

String fileToRun=txtPath.getText().toString()+"run this.exe -arg";
Runtime.getRuntime().exec(fileToRun, null, new File(txtPath.getText().toString()));

我也尝试将文件作为数组传递:

String fileToRun[]={txtPath.getText().toString(),"run this.exe"," -arg"};
Runtime.getRuntime().exec(fileToRun, null, new File(txtPath.getText().toString()));

无济于事。 当我尝试将其作为processbuilder运行时,会弹出同样的问题。 我将收到类似“文件C:\\ Program Files(x86)\\ thatsoftware \\ -arg”不存在的错误消息。很奇怪,因为传递了参数,但显然没有文件名。

当用户在文本框中键入整个字符串时,我可以设法运行它,但是如果我在代码中添加了参数和或文件名,则无法运行它。 谁能这么仁慈地向我解释一下,并告诉我如何仅用一个文本框就能做到?

您需要将可执行文件包装在转义引号\\“中,如下所示:

Runtime runtime = Runtime.getRuntime();
Process ps = runtime.exec("\"run this.exe\"");

或根据需要使用路径和参数:

Process ps = runtime.exec("\"C:\\Program Files (x86)\\Thatsoftware\\my exe.bat\" -arg");

据我所知,您必须将每个元素都放在单独的字段中:

String fileToRun[]={
                   txtPath.getText().toString(),
                   "run",
                   "this.exe",
                   " -arg"
                    };

我不知道您是否使用Swing ,但是Swing具有javax.swing.JFileChooser

//config fileChooser
    JFileChooser fc = new JFileChooser(lastOpenDir);

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setDialogTitle("Load Beacon List");
    fc.removeChoosableFileFilter(fc.getFileFilter());  //remove the default file filter
    FileFilter filter = new FileNameExtensionFilter("EXE file", "exe");
    fc.addChoosableFileFilter(filter); //add XML file filter

    //show dialog
    int returnVal = fc.showOpenDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION){

        File selectedDir = fc.getSelectedFile();
...

男孩,我感觉像个白痴吗... Java错误使我失望,但问题是在“运行this.exe”之前缺少斜杠。

太可惜了...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM