这几天做一个工具。需要把java程序生成exe,然后调用exe,并获取到其中的String 类型的返回值。
搜集了各种不同地方的帖子。今天整理一下,算是记录。
1、 先把java程序打成jar包。在myeclipse中,选择项目右键,Export.
此时点击finish,一路确定即可。期间都是些警告信息。
2、有了jar包,可以用其生成exe。用到的工具就是exe4j,下载地址exe4j下载官方地址
3、具体的使用方式,可以参考exe4j使用参考。不过我自己也写一遍,避免忘掉。特别声明:原文链接:https://blog.csdn.net/qq_32364027/article/details/79025543
(1)首先打开exe4j后,要先注册,不然生成的exe每次打开时,都会出现exe未注册的信息,选择右下角红框内按钮,在下一步填写注册信息。在此,提供一下注册码。
用户名和公司名可随便填
A-XVK258563F-1p4lv7mg7sav A-XVK209982F-1y0i3h4ywx2h1 A-XVK267351F-dpurrhnyarva
A-XVK204432F-1kkoilo1jy2h3r A-XVK246130F-1l7msieqiwqnq
(2)选择jre打压成exe
(3)填写程序名,并选择要输出的位置。
(3)填写文件名,选择图标,选择兼容环境。
注意这里离一定要选32位和64位运行环境
(4)选择jar包并选择主方法
(5)选择程序运行环境。默认出现的框内是有3个环境变量的,都删除,然后右侧添加按钮,选择Directory,找到自己运行环境的目录,选择就行
(6)到这一步,选择第二个后,一直默认next就行
(7)生成之后的目录结构是(将来用的时候,jre要随着exe一直保持同级目录,不能单独用exe程序)
(8)我的exe程序,需要在程序中读取配置文件中的配置信息。这就要在程序中用到当前exe的位置,以此作为坐标去找到配置文件位置。需要强调的是,获取当前exe运行的位置的方法,需要注意。我用的方法是
/**
* 获取当前项目路径
*/
public static String getExePath() {
return new File("").getAbsolutePath();
}
有些获取当前项目路径的方式,在jar包或exe中并不适用。但这种方式是有效了。
(9)在exe程序中,是可以给调用者返回String类型的数据的。用的方式就是
System.out.println(“这里是返回的String内容”);
调用者可以从流信息中读取到exe程序返回的内容。具体读取方式参照下边代码
package com;
import java.io.*;
public class T {
public static void main(String[] args) {
java.lang.Process process = null;
try {
String sourcePath = "E:\\a.xlsx";
String targetPath = "E:\\d.pdf";
String a = "cmd /c " + "E" + ": & cd " + "E:\\SzhtExcelUtil\\"
+ " & SzhtExcelUtil.exe \"" + sourcePath + "\" \""
+ targetPath + "\" \"y\" \"y\"";
process = Runtime.getRuntime().exec(a); //执行方法,调用exe程序 a是调用命令
ByteArrayOutputStream resultOutStream = new ByteArrayOutputStream();
InputStream errorInStream = new BufferedInputStream(process.getErrorStream());
InputStream processInStream = new BufferedInputStream(process.getInputStream());//拿到process中的流信息
int num = 0;
byte[] bs = new byte[1024];
while ((num = errorInStream.read(bs)) != -1) {
resultOutStream.write(bs, 0, num);
}
while ((num = processInStream.read(bs)) != -1) {
resultOutStream.write(bs, 0, num);
}
String result = new String(resultOutStream.toByteArray());//此处的result即为exe程序返回的字符串
System.out.println("exe程序返回的字符串为:" + result);
errorInStream.close();
errorInStream = null;
processInStream.close();
processInStream = null;
resultOutStream.close();
resultOutStream = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (process != null)
process.destroy();
process = null;
}
}
}