如何从独立的java程序中调用Java命令。
我理解Runtime.getRuntime()。exec(“cmd c / javac<> .java”);会工作。但是,这将是特定于平台的。
任何其他可用的API可以使它在j2sdk1.4中运行吗?
答案 0 :(得分:3)
如果您可以在同一个JVM中运行所有内容,则可以执行以下操作:
public class Launcher {
...
public static void main(String[] args) throws Exception {
launch(Class.forName(args[0]), programArgs(args, 1));
}
protected static void launch(Class program, String[] args) throws Exception {
Method main = program.getMethod("main", new Class[]{String[].class});
main.invoke(null, new Object[]{args});
}
protected static String[] programArgs(String[] sourceArgs, int n) {
String[] destArgs = new String[sourceArgs.length - n];
System.arraycopy(sourceArgs, n, destArgs, 0, destArgs.length);
return destArgs;
}
使用如下命令行运行它:
java Launcher OtherClassWithMainMethod %CMD_LINE_ARGS%
答案 1 :(得分:2)
调用Runtime.getRuntime()。exec()不仅是特定于平台的,而且效率极低。它会导致产生一个全新的shell和整个jvm,这可能会非常昂贵,具体取决于这个应用程序的依赖性(没有双关语意)。
执行“外部”Java代码的最佳方法是将其放在CLASSPATH中。如果必须调用应用程序的main方法,则只需导入并直接调用该方法即可。这可以这样做:
import my.externals.SomeMain
// call as if we are running from console
SomeMain.main(new String[] {"some", "console", "arguments"})
当然,最好的情况是简单地将其用作外部库并访问所需的代码而无需调用SomeMain.main()。坚持最佳实践并编写适当的封装模块化对象,可在其他应用程序使用时提供更大的可移植性和易用性。
答案 2 :(得分:0)
当您离开JVM并转移到系统命令时,您必须自己处理特定于平台的命令。 JVM提供了一种很好的抽象方法,为什么要离开呢?
如果要执行java特定的二进制文件,请查看java的ant库。您可以从执行平台依赖命令的java执行ant脚本。
答案 3 :(得分:0)
来自GAE的quercus php的Java编程:
import com.newatlanta.commons.vfs.provider.gae.GaeVFS;
import org.apache.commons.io.IOUtils;
import java.lang.Long;
import java.lang.Boolean;
GaeVFS::setRootPath(quercus_servlet_request()->getSession(true)->getServletContext()->getRealPath('/'));
define('VFSM', GaeVFS::getManager());
//VFSM->resolveFile('gae://gaevfs')->createFolder();
$file=VFSM->resolveFile('gae://gaevfs/tmp1');
//$file->createFile();
$text='pp';
$method=$file->getClass()->getDeclaredMethod('updateContentSize', array(Long::TYPE, Boolean::TYPE));
$method->setAccessible(true);
$method->invoke($file, strlen($text), true);
$out=$file->getContent()->getOutputStream();
IOUtils::write($text, $out, 'UTF8');
$out->close();
$in=$file->getContent()->getInputStream();
$method=$file->getClass()->getDeclaredMethod('doGetContentSize',array());
$method->setAccessible(true);
$len=$method->invoke($file);
$whole=IOUtils::toString($in, 'UTF8').':'.$len."<br>";
$in->close();
echo $whole;
GaeVFS::clearFilesCache();
GaeVFS::close();