简体   繁体   English

如何从Java中的命令提示符访问带有空格的文件路径

[英]How to access file path with spaces from command prompt in Java

I am trying to run a batch file from a Java program. 我正在尝试从Java程序运行批处理文件。 For instance: I have a batch "abc.bat" in a folder in "Program Files". 例如:我在“程序文件”的文件夹中有一个批处理“ abc.bat”。

I want to execute this batch from my Java Program. 我想从Java程序执行该批处理。 I am using CommandLine class, Commons-exec jar. 我正在使用CommandLine类,Commons-exec jar。

CommandLine cmdLine = CommandLine.parse("cmd");
cmdLine.addArgument("/c start \"\" \"C:\\Program Files\\abc.bat\"");

DefaultExecutor exec = new DefaultExecutor();
Process p = Runtime.getRuntime().exec(cmdLine.toString());
exec.execute(cmdLine);

The above code throws an error saying "Windows cant find the file. Make sure you typed the name correctly, and try again". 上面的代码引发错误,提示“ Windows无法找到该文件。请确保正确输入名称,然后重试”。 And, that is because of the spaces in the path. 而且,这是因为路径中有空格。

So, I tried the answer provided here by @brso05 and that works. 因此,我尝试了@ brso05在此处提供的答案,并且可以正常工作。 But I want it to be in a Future Class. 但我希望它能进入将来的班级。 Please find my code below and help me fix it. 请在下面找到我的代码,并帮助我修复它。

final CommandLine cmdLine = CommandLine.parse("cmd.exe");
cmdLine.addArgument("/c");
cmdLine.addArgument("start");
cmdLine.addArgument("\""+ batchFileExecute.getParent().toString() + "\"");

ExecutorService es = Executors.newFixedThreadPool(1);
Future<?> future = es.submit(new Runnable() {
        public void run() {
                DefaultExecutor exec = new DefaultExecutor();
                        try {
                            Process p = Runtime.getRuntime().exec(cmdLine.toString());
                            exec.execute(cmdLine);
                            System.out.println(p.waitFor());
                            }
                        catch (IOException e) 
                            {
                                e.printStackTrace();
                            }
                        catch (InterruptedException e)
                            {
                                e.printStackTrace();
                            }
                        }
                        });
                            String thread_status = null;
                            try 
                            {
                                thread_status = future.get().toString(); 
                                System.out.println(thread_status+" completed the execution");
                            } 
                            catch (NullPointerException e) 
                            {
                            System.out.println("The execution of the received project is     complete.");                   
// In here I want to do some processing again.
}

The code I mentioned works but it doesnt work if my batch file has a spaces in the path. 我提到的代码有效,但是如果我的批处理文件的路径中有空格,则该代码无效。 Can you help me fix this? 你能帮我解决这个问题吗?

Becuase the snippet you've given works but then I cant put it into Future. 因为您提供的摘录片段有效,但我无法将其放到Future中。 It doesnt work in the desired manner. 它不能以所需的方式工作。

Thanks in advance! 提前致谢!

This is an alternative way: 这是另一种方法:

     Runtime rt = Runtime.getRuntime();
     rt.exec("cmd.exe /c start \"\" \"C:\\Program Files\\abc.bat\"");

Have you tried with single quotes? 您是否尝试过使用单引号? According to this , it should work. 根据这个 ,它应该工作。

I had the same filenames with spaces issue while using ImageMagick. 使用ImageMagick时,我的文件名带有空格问题。 Here is the code to solve the issue: 这是解决问题的代码:

String imageOutput = null;
ByteArrayOutputStream identifyStdout = new ByteArrayOutputStream();
ByteArrayOutputStream identifyStderr = new ByteArrayOutputStream();

try
{
    DefaultExecutor identifyExecutor = new DefaultExecutor();
    // End the process if it exceeds 60 seconds
    ExecuteWatchdog identifyWatchdog = new ExecuteWatchdog(60000);
    identifyExecutor.setWatchdog(identifyWatchdog);


    PumpStreamHandler identifyPsh = new PumpStreamHandler(identifyStdout, identifyStderr);
    identifyExecutor.setStreamHandler(identifyPsh);
    identifyExecutor.setExitValue(0); //0 is success

    CommandLine identifyCommandline = new CommandLine("identify");
    identifyCommandline.addArgument(destFile.getAbsolutePath(), false);

    DefaultExecuteResultHandler identifyResultHandler = new DefaultExecuteResultHandler();

    identifyExecutor.execute(identifyCommandline, identifyResultHandler);
    identifyResultHandler.waitFor();

    if (identifyResultHandler.getExitValue() != 0)
    {
        String output = identifyStdout.toString();
        _logger.debug("Standard Out = " + output);
        _logger.debug("Standard Err = " + identifyStderr.toString());

        String msg = "ImageMagick overlay encountered an error. ImageMagick returned a value of " + identifyResultHandler.getExitValue();
        throw new Exception(msg);
    }
    else
    {
        imageOutput = identifyStdout.toString();
        _logger.debug("Standard Out = " + imageOutput);
        identifyStdout.close();
        identifyStderr.close();
    }
}
catch(Exception e)
{
    _logger.debug("Error: " + e.getLocalizedMessage(), e);
}
finally
{
    identifyStdout.close();
    identifyStderr.close();
}

The important part here is: 这里的重要部分是:

identifyCommandline.addArgument(destFile.getAbsolutePath(), false);

This line allows a filepath with spaces to process correctly. 该行允许带有空格的文件路径正确处理。

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

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