سؤال

I am attempting to write an GUI in Java that can send a users input to other files for processing, which is done using command line arguments. This works fine unless a user tries to send a string with whitespace, as they are interpreted as separate arguments. Here is an example:

public String exampleMethod(String userInput, String fileName)
{

    try 
    {
        String output = "";
        Process p = Runtime.getRuntime().exec("./directory/" + fileName + " " + userInput);
        BufferedReader in = new BufferedReader(
                            new InputStreamReader(p.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) 
        {
            output = output + line;
        }
        return output;
    }
    catch (IOException e) 
    {
        e.printStackTrace();
        return "ERROR: I/O Exception";
    }

Any help would be greatly appreciated

هل كانت مفيدة؟

المحلول

Spaces are used to separate argument. User should uses quotes (").

نصائح أخرى

You could use Java's built-in ProcessBuilder to do this. Something like:

Process p = new ProcessBuilder("./directory/" + fileName, userInput).start();

Alternatively, for something more robust, have a look at Apache's Commons Exec framework, though the code necessary is a bit more verbose.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top