我最近遇到过这个问题,并想知道是否有人可以帮助我阐明它。
我正在尝试从Java应用程序执行mongoexport,导出限制在特定的日期范围内。我构造了我的查询命令,并将其传递给Runtime.exec。这将返回代码2,说“位置选项太多”。
但是,如果我获取传递给exec的字符串(在下面注销),并在命令行上运行它,它可以完美地工作!
我把它缩小到“查询”参数 - 如果我不用这个构造命令,那么命令将通过Runtime.exec()完美地执行
我猜测它的一些编码问题与查询参数中的引号有关,但我不能在我的生活中弄清楚如何修复它。
以下是代码:
@Override
public void doWork() {
logger.info("Doing work");
//get the host for performing the mongo dump
String mongohome = GlimmerServer.config.getString("mongo.home");
String host = GlimmerServer.config.getString("mongo.dumphost");
String port = GlimmerServer.config.getString("mongo.dumpport");
String db = GlimmerServer.config.getString("mongo.dumpdb");
String collection = "stats_advert_daily";
String query = "'{date : new Date(1320451200000)}'"; //needs to be a proper query for mongo
String outputlocation = "/tmp/output.txt"; //needs to be asigned a random number name
String command = String.format(mongohome+"/bin/mongoexport " +
"--host %s " +
"--port %s " +
"--db %s " +
"--collection %s " +
"--query %s " +
"--fields _id,account_rid " +
"--out %s " +
"--slaveOk true " +
"--csv " +
"-vvvvv",
host,port,db,collection,query,outputlocation);
logger.info(command);
try{
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
StreamGobbler errorGobbler = new StreamGobbler(pr.getErrorStream(),"ERROR",logger);
StreamGobbler outputGobbler = new StreamGobbler(pr.getInputStream(),"OUTPUT",logger);
errorGobbler.start();
outputGobbler.start();
int exitVal = pr.waitFor();
logger.info(String.format("Process executed with exit code %d",exitVal));
}catch(Exception e){
logger.error(String.format("Error running task. Exception %s", e.toString()));
}
}
所有帮助表示赞赏!
干杯, 道格
答案 0 :(得分:1)
原来这与此问题有关:Command fails in script, works in command line
String query = "'{date : new Date(1320451200000)}'";
查询中的空格导致了一些解析问题。
此外,不需要单引号。因此,违规代码现在看起来像这样:
String query = "{date:Date(1320451200000)}";
现在,如果我将整个命令复制到shell中它不起作用(需要单引号),但是在Runtime.exec()中运行。
答案 1 :(得分:0)
String db = "Doctors";
String col = "patients";
String Host = "localhost";
String Port = "27017";
String fileName = "/home/gshewale/Documents/list.csv";
String name="\"name\"";
String patientname="\"Gaurav\"";
String command = "mongoexport --host " + Host + " --port " + Port + " --db " + db + " --collection " + col + " --type=csv --fields name --query {"+name+":"+patientname+"} --out " + fileName + "";
try {
System.out.println(command);
Process process = Runtime.getRuntime().exec(command);
int waitFor = process.waitFor();
System.out.println("waitFor:: " + waitFor);
} catch (Exception e) {
e.printStackTrace();
}
这对我有用.. !!!!