我们有一个调用我的Java程序的shell脚本。 该脚本传递了在中定义的方法的参数值 我的Java程序的主要方法。
参数的预期输入格式如下
"Test1, Test1_21APR15,XYZ,Test,Test, , , 2015-04-21"
"Test2, Test2_21APR15,XYZ,Test,Test, , ,2015-04-21"
"Test3,Test3_21APR15,XYZ, Test,Test, , ,2015-04-21"
等等,即每个字符串都有逗号分隔的属性,字符串用空格分隔(这里我在下一行中提到过,但实际值将用空格分隔)。
从上面的输入值我需要为本地属性赋值,如下所示:
attr1 = Test1,Test2,Test3
attr2 = Test1_21APR15,Test2_21APR15,Test3_21APR15
attr3 = XYZ,XYZ,XYZ
attr4 = Test,Test,Test
.
.
.
attr8 = 2015-04-21,2015-04-21,2015-04-21,
然后我需要在我的方法中处理这些参数。
我理解当你将参数传递给main方法时,它们被放在arg[]
数组中,但现在我在将参数值赋给属性时遇到了问题。
有人可以给我一些指导吗?提前谢谢。
答案 0 :(得分:1)
If you pass each set as "," separated instead of space separated like
"Test1, Test1_21APR15,XYZ,Test,Test, , , 2015-04-21, Test2, Test2_21APR15,XYZ,Test,Test, , ,2015-04-21"
Then we could use following logic Here "testnum" is number of input lines we are referring and "testlen" is number of strings in each line.
for(int i=0;i<testlen;i++){
for(int j=0;i<testnum;j++){
attr[i]=attr[i]+args[j*testlen+i]
if(j<testnum-1)
attr[i]=attr[i]+",";
}
}
答案 1 :(得分:0)
您可以将命令行参数传递给JAVA主类,如下所示:
java TestMain "Test1, Test1_21APR15,XYZ,Test,Test, , , 2015-04-21" "Test2, Test2_21APR15,XYZ,Test,Test, , ,2015-04-21" "Test3,Test3_21APR15,XYZ, Test,Test, , ,2015-04-21"
这里TestMain类的内容是
public class TestMain {
public static void main(String[] args) {
String attr0=args[0];
String attr1=args[1];
String attr2=args[2];
......................use attributes here..............
}
}
答案 2 :(得分:0)
public class YourClass {
public static void main (String[] args) {
if (args == null) {
System.out.println("No arguments supplied, exiting");
System.exit(0);
}
// length() is wrong
int numAttr = args[0].split(",").length;
String[] attr = new String[numAttr];
for (int i=0; i < args.length; ++i) {
String[] parts = args[i].split(",");
for (int j=0; j < parts.length; ++j) {
if (i > 0) {
attr[j] += ",";
}
attr[j] += parts[j];
}
}
}
}
您可以遍历attr
数组以提取所需的各种值:
for (int i=0; i < attr.length; ++i) {
System.out.println("attr" + (i+1) + "= " + attr[i]);
}
<强>输出强>
attr1 = Test1,Test2,Test3
attr2 = Test1_21APR15,Test2_21APR15,Test3_21APR15
attr3 = XYZ,XYZ,XYZ
attr4 = Test,Test,Test
.
.
.
attr8 = 2015-04-21,2015-04-21,2015-04-21
答案 3 :(得分:0)
The parameters can be passed as :
java CommadLineArguments "parm1, param2" "param3, param4" ...
Here space is the delimiter for the jvm. It will split with space as delimeter and fill the args array.
The class will be :
public class CommadLineArguments {
public static void main(String[] args) {
if (args == null) {
System.out.println(" No Arguments ");
} else {
String att1 = args[0];
String att2 = args[1];
}
}
}
答案 4 :(得分:0)
在我看来,每个args-string中逗号分隔值的数量是由数据模型强制的。
所以我建议下面的解决方案。它不像其他提案那样简短或通用,但可能符合您的要求。
\\