1 pom
<web3j.version>4.2.0</web3j.version>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>${web3j.version}</version>
</dependency>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>codegen</artifactId>
<version>${web3j.version}</version>
</dependency>
2 生成代码:需要先生成abi和bin文件,再生成Java文件
try {
// 生成的java类名,同ABI文件同名,自动首字母大写
String packageName = "";
String outDirPath = "D:\\temp";
String binDirPath = "D:\\temp\\test2.bin";
String abiDirPath = "D:\\temp\\test.abi";
String[] arr = Arrays.asList(
"-b", binDirPath,
"-a", abiDirPath,
"-p", packageName,
"-o", outDirPath
).toArray(new String[0]);
SolidityFunctionWrapperGenerator.main(arr);
} catch (Exception e) {
log.error("生成智能合约Java文件失败", e);
}
3 response输出流
// 下载
InputStream is = null;
ServletOutputStream os = null;
try{
is = new FileInputStream("生成的Java文件path");
os = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment; filename=Test.java");
IoUtil.copy(is, os);
}catch (Exception e){
log.error("下载智能合约Java文件失败", e);
}finally {
try {
if(is != null){
is.close();
}
} catch (IOException e) {
log.error("关闭流失败", e);
}
try {
if(os != null) {
os.flush();
os.close();
}
} catch (IOException e) {
log.error("关闭流失败", e);
}
}
abi和bin文件说明:
abi文件内容:智能合约编译后生成的abi
bin文件内容:智能合约编译后生成的bytecode
再附加一个,将字符串写入到文件的方法:
/**
* 生成文件
*
* @param path 文件路径
* @param content 内容
*/
public void generateFile(String path, String content) {
File file = new File(path);
if(!file.exists()){
try {
boolean result = file.createNewFile();
if(!result){
throw new BusinessException();
}
} catch (IOException e) {
log.error("创建文件失败:"+path, e);
throw new BusinessException("生成合约文件失败");
}
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
} catch (FileNotFoundException e) {
log.error("找不到对应文件:"+path, e);
throw new BusinessException("生成合约文件失败");
}
IoUtil.writeUtf8(os, true, content);
}
完。