在服务器上面运行java程序时,常常需要输入参数,为了防止记不住或者位置出错等问题,需要给出相关的提示,好在这个很容易实现。
首先下载 common-cli这个jar包,可以从这里下载:http://commons.apache.org/proper/commons-cli/
然后把jar包添加到工程中去,在传递参数时添加如下代码:
String source_path;
String output_path;
int cluster_num = 10;
int iterator_num = 10;
Options options = new Options();
options.addOption("h", false, "help"); //参数不可用
options.addOption("i", true, "input file path"); //参数可用
options.addOption("o", true, "output file path"); //参数可用
options.addOption("c", true, "cluster number, default 10"); //参数可用
options.addOption("x", true, "iterator number, default 10"); //参数可用
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("i"))
{
source_path = cmd.getOptionValue("i");
}else{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "help", options );
return;
}
if (cmd.hasOption("o"))
{
output_path = cmd.getOptionValue("o");
}else{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "help", options );
return;
}
if (cmd.hasOption("c"))
{
cluster_num = Integer.parseInt(cmd.getOptionValue("c"));
}
if (cmd.hasOption("x"))
{
iterator_num = Integer.parseInt(cmd.getOptionValue("c"));
}
if (cmd.hasOption("h"))
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "help", options );
}
以后调用就可以使用上面的变量了。
Word2VEC vec = new Word2VEC();
vec.loadVectorFile(source_path);
System.out.println("load data ok!");
//input cluster number and iterator number
WordKmeans wordKmeans = new WordKmeans(vec.getWordMap(), cluster_num,iterator_num);
Classes[] explain = wordKmeans.explain();
File fw = new File(output_path);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fw), "UTF-8"));