1、下載官方的源代碼:https://codeload.github.com/happyfish100/fastdfs-client-java/zip/master
2、采用maven命令編譯成jar安裝到本地maven庫:mvn clean install
3、在Java程序中使用它提供的API來訪問fastDFS文件系統;
注:maven官網的客戶端有點問題,需要自己生成jar包
執行mvn clean install后,會出現在本地倉庫中
測試代碼如下
工具類
package com.topcheer.fastdfs; import java.io.IOException; import org.csource.fastdfs.ClientGlobal; import org.csource.fastdfs.StorageClient; import org.csource.fastdfs.StorageServer; import org.csource.fastdfs.TrackerClient; import org.csource.fastdfs.TrackerServer; public class FastDfsUtil { private static final String conf = "fastdfs-client.conf"; private static TrackerServer trackerServer = null; private static StorageServer storageServer = null; public static StorageClient getStorageClient() { StorageClient storageClient = null; try { // 1 初始化配置文件 ClientGlobal.init(conf); // 2 創建tracker的客戶端對象 TrackerClient client = new TrackerClient(); // 3 創建tracker的服務器對象 trackerServer = client.getConnection(); // 4 創建storage的客戶端對象 storageServer = client.getStoreStorage(trackerServer); // 5 創建storage的服務器對象 storageClient = new StorageClient(trackerServer, storageServer); } catch (Exception e) { e.printStackTrace(); } return storageClient; } //關閉資源 public static void close() { if (trackerServer != null) { try { trackerServer.close(); } catch (IOException e) { e.printStackTrace(); } } if (storageServer != null) { try { storageServer.close(); } catch (IOException e) { e.printStackTrace(); } } } }
fastdfs-client.conf配置信息
tracker_server = 192.168.180.104:22122
上傳
public static void uploadFile() { try { String[] strings = FastDfsUtil.getStorageClient().upload_appender_file("C:\\Users\\asus\\Desktop\\激活碼.txt", "txt", null); Arrays.asList(strings).forEach(s -> System.out.println(s)); //group1 // M00/00/00/wKi0aF3II2yEPlv6AAAAAHp_ifU838.txt } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); }finally { FastDfsUtil.close(); } }
注:nginx.conf的端口被改成8888了,測試結果如圖
下載
public static void downfile() { try { FastDfsUtil.getStorageClient().download_file("group1", "M00/00/00/wKi0aF3II2yEPlv6AAAAAHp_ifU838.txt", "d:/a.txt"); } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); }finally { FastDfsUtil.close(); } }
刪除
/** * delete file from storage server * * @param group_name the group name of storage server * @param remote_filename filename on storage server * @return 0 for success, none zero for fail (error code) */ public static void delFile() { try { int file = FastDfsUtil.getStorageClient().delete_file("group1", "M00/00/00/wKi0aF3II2yEPlv6AAAAAHp_ifU838.txt"); System.out.println(file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MyException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { FastDfsUtil.close(); } }