在java中执行外部命令

在java中执行外部命令

本文介绍了在java中执行外部命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在java中执行一个没有使用ProcessBuilder的启动开销(慢)的命令?

Is there a way to execute a command in java that doesn't suffer from the startup overhead (slowness) of using ProcessBuilder?

更多细节:我正在使用im4java是一个java库,它在内部使用ProcessBuilder来执行imagemagick的程序。这很慢。我创建了一个小单元测试,显示ProcessBuilder(不是im4java)是问题所在。缓慢是使用ProcessBuilder的启动开销。我发现互联网上有帖子说过程序员有开销,所以不仅仅是我这么说。

More detail: I am using im4java which is a java library that internally uses ProcessBuilder to execute imagemagick's programs. It is slow. I have created a small unit test that shows that ProcessBuilder (not im4java) is the problem. The slowness is the startup overhead of using ProcessBuilder. I have found posts around the internet saying processbuider has overhead so its not just me saying it does.

List<String> commands = new ArrayList<String>();
commands.add("C:\\PROGRA~2\\ImageMagick-6.6.4-Q16\\convert.exe");
commands.add("dog.jpg");
commands.add("output.jpg");
ProcessBuilder processBuilder = new ProcessBuilder(commands);
Process start = processBuilder.start();
start.waitFor();


推荐答案

这不推荐,但你可以写一个JNI库可以执行与ProcessBuilder相同的操作。也许你会更快,但我不会指望它,加上你会失去跨平台的兼容性。

This is not recommended, but you could write a JNI library to do the same thing that ProcessBuilder is doing. Perhaps yours would be faster, but I wouldn't count on it, plus you would lose cross-platform compatibility.

我们在这里说话的速度有多慢?我正在使用 ProcessBuilder 来运行Git命令(还没有机会查看JGit),而且看起来很活泼。你可能在Linux上有更好的运气,因为开销可能实际上是在Windows重量级进程创建中。

How slow are we talking here? I'm using ProcessBuilder myself for running Git commands (haven't had a chance to look into JGit yet), and it seems snappy enough. You may have better luck on Linux, as the overhead may actually be in Windows heavyweight process creation.

这篇关于在java中执行外部命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:35