Issue with Command Line arguments which got spaces in it

匿名 (未验证) 提交于 2019-12-03 02:35:01

问题:

I was struck in a weird problem , for which i found out the cause of reason , after lot of debugging . I have a Java program which i am executing in Linux environment through a bash script .

This is my simple bash script , which accepts a String .

#!/bin/bash java -cp  com.QuoteTester $1 

The issue is that the command line argument can be with Spaces or Without spaces . For example it can be either

Apple Inc. 2013 Jul 05 395.00 Call     OR  Apple 

As per my code it is this way

public static void main(String[] args)  { String symbol = args[0];  if (symbol.trim().contains(" ")) // Option {  }  else  // Stock  {  } 

So the issue is that , when i am trying to execute it this way

./quotetester Apple Inc. 2013 Jul 05 395.00 Call

its only always going to the else condition that is Stock .

Is there anyway i can resolve this ??

回答1:

When you pass command line arguments with spaces, they are taken as space separated arguments, and are splitted on space. So, you don't actually have a single argument, but multiple arguments.

If you want to pass arguments with spaces, use quotes:

java classname "Apple Inc. 2013 Jul 05 395.00 Call" 


回答2:

This is not a Java issue per se. It's a shell issue, and applies to anything you invoke with such arguments. Your shell is splitting up the arguments and feeding them separately to the Java process.

You have to quote the arguments such that the shell doesn't split them up. e.g.

$ java  -cp ... "Apple Inc. 2013" 

etc. See here for a longer discussion.



回答3:

The arguments are handled by the shell , so any terminal settings should not affect this. You just need to have quoted argument and it should work.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!