Spaces are used to separate argument. User should uses quotes (").
Preserving whitespace in a String when using as a command line argument
-
10-07-2023 - |
Question
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
Solution
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow