以太坊:智能合约java类的生成并下载

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);
    }

 

 

 

完。

 

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值