Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | Github | OSChina 博客 | 云社区 | 云栖社区 | Facebook | Linkedin | 视频教程 | 打赏(Donations) | About
知乎专栏多维度架构微信号 netkiller-ebook | QQ群:128659835 请注明“读者”

37.4. java-ipfs-api

37.4.1. Maven 配置

		
  <repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
  </repositories>

	<dependencies>
		<dependency>
			<groupId>com.github.ipfs</groupId>
			<artifactId>java-ipfs-api</artifactId>
			<version>v1.2.1</version>
		</dependency>
		<dependency>
			<groupId>com.github.multiformats</groupId>
			<artifactId>java-multibase</artifactId>
			<version>v1.0.1</version>
		</dependency>
		<dependency>
			<groupId>com.github.multiformats</groupId>
			<artifactId>java-multiaddr</artifactId>
			<version>v1.3.1</version>
		</dependency>
		<dependency>
			<groupId>com.github.multiformats</groupId>
			<artifactId>java-multihash</artifactId>
			<version>v1.2.1</version>
		</dependency>
		<dependency>
			<groupId>com.github.ipld</groupId>
			<artifactId>java-cid</artifactId>
			<version>v1.1.1</version>
		</dependency>
	</dependencies>		
		
		

37.4.2. 查看版本号

		
package cn.netkiller.ipfs;

import io.ipfs.api.IPFS;

public class Demo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/5001");
			System.out.println(ipfs.version());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
		
		

运行后显示 ipfs 版本号表示链接成功

37.4.3. 添加文件到 IPFS

首先创建一个测试文件

		
neo@MacBook-Pro ~ % echo "Helloworld" >  /tmp/hello.txt
neo@MacBook-Pro ~ % cat /tmp/hello.txt                 
Helloworld
		
		

添加本地文件到IPFS

		
	NamedStreamable.FileWrapper file = new NamedStreamable.FileWrapper(new File("/tmp/hello.txt"));
	System.out.println(ipfs.add(file).get(0).toJSON());
		
		

输出结果

		
{Hash=QmS8R3nSbDHjQ7WRTjtX1pkiQ6BUpti9qTjweZkBgGPKiN, Links=[], Name=hello.txt, Size=19}
		
		

输出字符串 toJSONString()

		
		NamedStreamable.FileWrapper file = new NamedStreamable.FileWrapper(new File("/tmp/hello.txt"));		
		MerkleNode addResult = ipfs.add(file).get(0);
		System.out.println(addResult.toJSONString());		
		
		
		
{"Hash":"QmS8R3nSbDHjQ7WRTjtX1pkiQ6BUpti9qTjweZkBgGPKiN","Links":[],"Name":"hello.txt","Size":"19"}		
		
		
[提示]提示

注意:文件名不会影响 Hash 值得变化

37.4.4. 添加文本到 IPFS

		
	public Object put() throws IOException {
		NamedStreamable.ByteArrayWrapper text = new NamedStreamable.ByteArrayWrapper("url.txt", "http://www.netkiller.cn".getBytes());
		MerkleNode addResult = ipfs.add(text).get(0);
		return addResult.toJSON();
	}		
		
		

返回结果

		
{Hash=QmY1ZUDzCH7J2QcVPLWT6FKwhaVvnkFRY89GMvbD27Eyde, Links=[], Name=url.txt, Size=31}
		
		
[提示]提示

注意:文件名不会影响 Hash 值得变化

37.4.5.