以太坊:智能合約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);
    }

 

 

 

完。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章