是否可以使Java可执行文件? [英] Is it possible to make a Java executable?

查看:137
本文介绍了是否可以使Java可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要明确的是,可执行文件并不是要为处理器准备好文字字节.例如,当将解释器添加到顶部以指定脚本应由/bin/bash/bin/sh或任何要解释它的程序运行时,被解释且不可执行的bash脚本将变为可执行文件.

To be clear, by executable I do not mean literal bytes ready for the processor. For example a bash script, which is interpreted and not executable, becomes executable when a shebang is added to the top that specifies the script should be run by /bin/bash or /bin/sh or whatever program will be interpreting it.

我想知道是否可以使用Java,Java从技术上讲不是一种脚本语言,但绝对不能执行.似乎Java很难,因为用户实际上没有机会在编译文件中添加shebang,并且编译后的Java不能来自stdin.

I was wondering if it's possible to do with Java, which is not technically a scripting language but is definitely not executable. It seems like Java would be hard because the user doesn't actually have the opportunity to add a shebang to the compiled file, and the compiled java cannot come from stdin.

推荐答案

两年半后,我偶然发现了比2016年更完整的答案. Java二进制文件可以嵌入可执行文件中, 本文解释了如何通过

After two and a half years I have stumbled upon a more complete answer than was given in 2016. The Java binaries can be embedded within the executable, contrary to John Hascall's answer. This article explains how this can be done in linux and unix like systems by adding a binary payload to a shell script.

我将简要介绍该过程.

给出一个名为any_java_executable.jar的可执行jar
给出,您要创建一个名为my_executable的可执行文件
给出一个名为basis.sh的脚本文件,其中包含以下内容

Given an executable jar named any_java_executable.jar
Given you want to create an executable named my_executable
Given a script file named basis.sh with the following contents

#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt 0 -a -f "$0" ] && MYSELF="./$0"
java=java
if test -n "$JAVA_HOME"; then
    java="$JAVA_HOME/bin/java"
fi
exec "$java" $java_args -jar $MYSELF "$@"
exit 1

可以通过运行以下两个命令来创建本机可执行文件.

The native executable can be created by running the following two commands.

cat basis.sh any_java_executable.jar > my_executable;
chmod +x my_executable;

然后my_executable是一个本机可执行文件,能够运行Java程序,而无需依赖jar文件的位置.可以通过运行来执行

Then my_executable is a native executable capable of running the java program without depending on the location of the jar file. It can be executed by running

./my_executable [arg1 [arg2 [arg3...]]]

,如果放置在/usr/local/bin中,则可以在任何地方用作CLI工具.

and can be used anywhere as a CLI tool if placed in /usr/local/bin.

这篇关于是否可以使Java可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆