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.