我最近遇到了这个问题,想知道是否有人可以帮助我解释一下。
我正在尝试从 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()));
}
}
所有帮助表示赞赏!
干杯,道格