java利用nfs-client连接nfs,读取/下载/上传文件

引入pom

        <dependency>
            <groupId>com.emc.ecs</groupId>
            <artifactId>nfs-client</artifactId>
            <version>1.0.3</version>
        </dependency>
NfsUtil
package xxx;

import com.emc.ecs.nfsclient.nfs.io.Nfs3File;
import com.emc.ecs.nfsclient.nfs.io.NfsFileInputStream;
import com.emc.ecs.nfsclient.nfs.io.NfsFileOutputStream;
import com.emc.ecs.nfsclient.nfs.nfs3.Nfs3;
import com.emc.ecs.nfsclient.rpc.CredentialUnix;
import lombok.var;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @描述 NFS工具类
 * @参考文档 https://www.cnblogs.com/yshyee/p/9520181.html
 * @参考文档 https://blog.csdn.net/ZYQ_1004/article/details/104947117
 * @参考文档 https://blog.csdn.net/fromfire2/article/details/123695955
 */
public class NfsUtil {
    private static final String NFS_IP = "xxx.xxx.xxx.xxx";
    private static final String NFS_DIR = "/xxx/xxx";//这个结尾有没有/不影响,可以填入子路径

    static Nfs3 client;

    static {
        try {
            client = new Nfs3(NFS_IP, NFS_DIR, new CredentialUnix(), 3);
        } catch (Exception e) {
            LogUtil.log(e.getMessage());
            e.printStackTrace();
        }
    }

    public static Nfs3File getFile(String path) {
        try {
            if (!path.startsWith("/"))
                path = "/" + path;//无论NFS_DIR末尾带不带/,这里开头必须/,否者堆栈溢出
            return client.newFile(path);
        } catch (Exception e) {
            LogUtil.log(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public static List<Nfs3File> getRootFiles() throws IOException {
        return getFile("/").listFiles();
    }

    public static InputStream read(Nfs3File file) throws IOException {
        return new NfsFileInputStream(file);
    }

    public static InputStream read(String path) throws IOException {
        return read(getFile(path));
    }

    public static String readText(String path) throws IOException {
        return BinaryUtil.readText(read(path));
    }

    public static void upload(String path, byte[] data) throws IOException {
        var file = getFile(path);
        BinaryUtil.write(new NfsFileOutputStream(file), data);
    }

    public static void upload(String path, InputStream data) throws IOException {
        upload(path, BinaryUtil.getBytes(data));
    }

    public static void upload(String path, String text) throws IOException {
        upload(path, BinaryUtil.getBytes(text));
    }

    public static void test() throws IOException {
        var path = StringUtil.guid(".txt");
        upload(path, "中国智造,惠及全球");
        var text = readText(path);
        LogUtil.log(text);
        LogUtil.log(getRootFiles());
    }
}

下面是用到的工具类,如果你需要,一般用不到,自己项目都有封装

BinaryUtil
package xxx;

import cn.hutool.core.util.HashUtil;
import lombok.var;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class BinaryUtil {

    public static ByteArrayOutputStream getMemoryOutputStream() {
        return new ByteArrayOutputStream();
    }

    public static ByteArrayOutputStream getMemoryOutputStream(InputStream inputStream) throws IOException {
        var byteArrayOutputStream = new ByteArrayOutputStream();
        int _byte;
        while ((_byte = inputStream.read()) != -1)
            byteArrayOutputStream.write(_byte);
        inputStream.close();
        return byteArrayOutputStream;
    }

    public static ByteArrayInputStream getMemoryInputStream(ByteArrayOutputStream output) {
        return new ByteArrayInputStream(output.toByteArray());
    }

    public static ByteArrayInputStream getMemoryInputStream(InputStream inputStream) throws IOException {
        return getMemoryInputStream(getMemoryOutputStream(inputStream));
    }

    public static byte[] readBytes(InputStream inputStream) throws IOException {
        var stream = getMemoryOutputStream(inputStream);
        var data = stream.toByteArray();
        stream.close();
        return data;
    }

    public static byte[] getBytes(InputStream inputStream) throws IOException {
        return readBytes(inputStream);
    }

    public static byte[] getBytes(String text) {
        return text.getBytes(StandardCharsets.UTF_8);
    }

    public static InputStream getStream(byte[] data) {
        return new ByteArrayInputStream(data);
    }

    public static InputStream getStream(String text) {
        return getStream(getBytes(text));
    }

    public static String readText(InputStream inputStream, String charset) throws IOException {
        var stream = getMemoryOutputStream(inputStream);
        var text = stream.toString(charset);
        stream.close();
        return text;
    }

    public static String readText(InputStream inputStream) throws IOException {
        return readText(inputStream, StandardCharsets.UTF_8.name());
    }


    public static void write(OutputStream outputStream, byte[] data) throws IOException {
        outputStream.write(data);
        outputStream.close();
    }

    public static void write(OutputStream outputStream, InputStream data) throws IOException {
        write(outputStream, getBytes(data));
    }

    public static void write(OutputStream outputStream, String text) throws IOException {
        write(outputStream, getBytes(text));
    }

    public static long getHashCode(InputStream inputStream) throws IOException {
        return HashUtil.cityHash32(getBytes(inputStream));
    }

}

 StringUtil 

package xxx;

import lombok.var;
import org.springframework.util.StringUtils;

import java.util.*;

public class StringUtil {

    public static boolean equals(String value, String... keywords) {
        for (var keyword : keywords)
            if (keyword.equals(value))
                return true;
        return false;
    }

    public static boolean equals(Integer value, Integer... keywords) {
        for (var keyword : keywords)
            if (keyword == value)
                return true;
        return false;
    }

    public static boolean like(String value, String... keywords) {
        if (value == null)
            return false;
        for (var keyword : keywords)
            if (keyword.contains(value))
                return true;
        return false;
    }

    public static <T> String join(List<T> list) {
        var builder = new StringBuilder();
        for (var index = 0; index < list.size(); index++) {
            if (builder.length() != 0)
                builder.append(",");
            builder.append(list.get(index));
        }
        return builder.toString();
    }

    public static String addSingleQuotationMarks(String value) {
        if (value.startsWith("'"))
            return value;
        return "'" + value + "'";
    }

    public static String addDoubleQuotationMarks(String value) {
        if (value.startsWith("\""))
            return value;
        return "\"" + value + "\"";
    }

    public static String[] removeEmpty(String[] array) {
        var list = LinqUtil.filter(array, m -> isNotEmpty(m));
        return list.toArray(new String[0]);
    }

    public static boolean contains(String[] values, String keyword) {
        for (var value : values) {
            if (value.equals(keyword))
                return true;
        }
        return false;
    }

    public static boolean in(String value, String... values) {
        for (var item : values)
            if (item.equals(value))
                return true;
        return false;
    }

    public static List<String> list(List<?> values) {
        var list = new ArrayList<String>();
        for (var value : values)
            list.add(value.toString());
        return list;
    }

    public static String digit2Hanzi(String value) {
        return value.replace('0', '零')
                .replace('1', '一')
                .replace('2', '二')
                .replace('3', '三')
                .replace('4', '四')
                .replace('5', '五')
                .replace('6', '六')
                .replace('7', '七')
                .replace('8', '八')
                .replace('9', '九');
    }

    public static boolean contains(String text, String keyword) {
        if (keyword == null || text == null)
            return false;
        return text.contains(keyword);
    }

    public static String getSex(Integer sex) {
        if (sex == 0)
            return "男";
        if (sex == 1)
            return "女";
        return "";
    }

    public static String[] combination(String[] array1, String[] array2, String spo) {
        var list = new ArrayList<String>();
        for (var item1 : array1)
            for (var item2 : array2)
                list.add(item1 + spo + item2);
        return ArrayUtil.toArray(list, array1);
    }

    public static String[] getDistinct(String[] array) {
        List list = Arrays.asList(array);
        Set set = new HashSet(list);
        return (String[]) set.toArray(new String[0]);
    }

    public static boolean contains(List<String> keywords, String keyword) {
        for (var value : keywords) {
            if (value.equals(keyword))
                return true;
        }
        return false;
    }

    public static List<String> split(String text) {
        if (text == null)
            return new ArrayList<>();
        var array = text.split(",");
        return ArrayUtil.arrayToList(array);
    }

    public static String listToStringSplit(List list, String split) {
        if (list == null || list.size() == 0)
            return null;

        return StringUtils.trimAllWhitespace(list.toString()
                .replaceAll("\\[", "")
                .replaceAll("]", ""))
                .replaceAll(",", split);
    }

    public static String listToStringSplit(List list, String split, boolean isTrimSpace) {
        if (list == null || list.size() == 0)
            return null;
        if (isTrimSpace) {
            return listToStringSplit(list, split);
        }
        return list.toString()
                .replaceAll("\\[", "")
                .replaceAll("]", "")
                .replaceAll(",", split);
    }

    public static List joinList(List list, String startJoin, String endJoin) {
        if (list == null || list.size() == 0)
            return null;
        for (int i = 0; i < list.size(); i++) {
            list.set(i, joinString(list.get(i), startJoin, endJoin));
        }
        return list;
    }

    public static String joinString(Object obj, String startJoin, String endJoin) {
        String value = obj.toString();
        if (isEmpty(value))
            return null;
        value = startJoin + value + endJoin;
        return value;
    }

    public static List<String> getLetters(String text) {
        var list = new ArrayList<String>();
        for (var ch : text.toCharArray())
            list.add(ch + "");
        return list;
    }

    public static String newId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String newId(int length) {
        return newId().substring(0, length);
    }

    public static String guid(String tail) {
        return newId() + tail;
    }

    public static boolean isEmpty(Object text) {
        return StringUtils.isEmpty(text);
    }

    public static boolean isNotEmpty(Object... values) {
        for (var value : values)
            if (StringUtils.isEmpty(value))
                return false;
        return true;
    }

    public static String format(Object value, Object... args) {
        if (value == null)
            return "";
        if (args.length > 0)
            return String.format(value.toString().replace("{}", "%s"), args);
        return value.toString();
    }

    public static String number(long value, int length) {
        return String.format("%0" + length + "d", value);
    }

    public static String number(int value, int length) {
        return String.format("%0" + length + "d", value);
    }

    public static String upperFirst(String value) {
        char[] cs = value.toCharArray();
        if (cs[0] > 96 && cs[0] < 123)
            cs[0] -= 32;
        return String.valueOf(cs);
    }

    public static String[] upperFirst(String[] values) {
        for (var index = 0; index < values.length; index++)
            values[index] = upperFirst(values[index]);
        return values;
    }

    public static String join(String[] values, String spor) {
        var sb = new StringBuilder(values[0]);
        for (int index = 1; index < values.length; index++) {
            sb.append(spor);
            sb.append(values[index]);
        }
        return sb.toString();
    }

    public static String join(List<String> values, String spor) {
        return join(ArrayUtil.toArray(values, new String[0]), spor);
    }

}
LogUtil
package xxx;

import cn.hutool.json.JSONUtil;
import lombok.var;

public class LogUtil {

    static int count;

    public static void log(Object value, Object... args) {
        var msg = StringUtil.format(value, args);
        System.out.println(StringUtil.format("\r\n[{}][{}][LogUtil]\r\n" +
                        "╭───────────────────────────────────────────────────────────────────────────────────────────╮" +
                        "\r\n{}\r\n" +
                        "╰━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╯",
                ++count,
                TimeUtil.getNowString(TimeUtil.format_ymdhmss),
                msg));
    }

    public static void info(Object value, Object... args) {
        log(value, args);
    }

    public static void debug(Object value, Object... args) {
        log(value, args);
    }

    public static void json(Object value) {
        if (value == null)
            log("null");
        log(JSONUtil.toJsonStr(value));
    }

    public static void log() {
        log(null);
    }

    public static void logJson(Object value) {
        json(value);
    }

}

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

上海好程序员

给上海好程序员加个鸡腿!!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值